Javascript ImageData Drawing Is Scaling Incorrectly - javascript

The idea of the program is to have an image of a map and to overlay a black canvas on that map. Then the user will click on some part of the canvas and, similar to a spray paint tool, the pixels near the mouse will become transparent on the canvas. Thus, the map will be shown (like a fog of war type feature). When I click near the top left of the canvas the spray paint works sort of as intended but as I click further right and down the canvas the pixels that get turned transparent are way further right and down... Any idea what is wrong here? Here is the code:
// On document ready function.
$(document).ready(function() {
canvas = document.getElementById("myImageDisplayerCanvas");
drawingContext = canvas.getContext("2d");
drawingContext.fillStyle = "#000000";
drawingContext.fillRect(0, 0, 800, 554);
});
// Spray paint logic.
var _intervalId, // used to track the current interval ID
_center, // the current center to spray
density = 10,
radius = 10,
drawingCxt,
leftClickPressed,
drawingContext,
canvas;
function getRandomOffset() {
var randomAngle = Math.random() * 360;
var randomRadius = Math.random() * radius;
return {
x: Math.cos(randomAngle) * randomRadius,
y: Math.sin(randomAngle) * randomRadius
};
}
this.startDrawing = function(position) {
_center = position;
leftClickPressed = true;
// spray once every 10 milliseconds
_intervalId = setInterval(this.spray, 10);
};
this.moveDrawing = function(position) {
if (leftClickPressed) {
clearInterval(_intervalId);
_center = position;
// spray once every 10 milliseconds
_intervalId = setInterval(this.spray, 10);
}
}
this.finishDrawing = function(position) {
clearInterval(_intervalId);
leftClickPressed = false;
};
this.spray = function() {
var centerX = parseInt(_center.offsetX),
centerY =
parseInt(_center.offsetY),
i;
for (i = 0; i < density; i++) {
var offset = getRandomOffset();
var x = centerX + parseInt(offset.x) - 1,
y = centerY +
parseInt(offset.y) - 1;
var dy = y * 800 * 4;
var pos = dy + x * 4;
var imageData = drawingContext.getImageData(0, 0, 800, 554);
imageData.data[pos++] = 0;
imageData.data[pos++] = 0;
imageData.data[pos++] = 0;
imageData.data[pos++] = 0;
drawingContext.putImageData(imageData, 0, 0);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="myImageDisplayerDiv" style="position:relative; width:800px; height:554px">
<img src="~/images/RedLarch.jpg" style="width:800px; height:554px; top: 0; left: 0; position: absolute; z-index: 0" />
<canvas id="myImageDisplayerCanvas" onmousedown="startDrawing(event)" onmousemove="moveDrawing(event)" onmouseup="finishDrawing(event)" style="width:800px; height:554px; top: 0; left: 0; position: absolute; z-index: 1; opacity: 1; fill: black" />
</div>

Set canvas resolution.
The reason the spray is offset is because you have not set the canvas resolution. You set the resolution via the canvas element width and height properties
<canvas id="canvas" width="800" height="554"></canvas>
Setting the style width and height sets the canvas display size not the resolution. If you don't set the canvas resolution it defaults to 300 by 150.
There were many other problems with your code.
Getting the whole canvas image data just to set a single pixel is way overkill. Just create a single pixel imageData object and place that pixel where needed
Use requestAnimationFrame to sync with the display, never use setInterval or setTimeout as they are not synced to the display hardware and will cause you endless problems.
Create a single mouse event function to handle all the mouse events and just record the mouse state. Use the main loop called by requestAnimationFrame to handle the drawing, never draw from a mouse event.
You don't need to define functions with this.functionName = function(){} if the function is not part of an object.
Trig function use radians not degrees. 360 deg in radians is 2 * Math.PI
Below is a quick rewrite of you code using the above notes.
const ctx = canvas.getContext("2d");
requestAnimationFrame(mainLoop); // start main loop when code below has run
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 800, 554);
// create a pixel buffer for one pixel
const imageData = ctx.getImageData(0, 0, 1, 1);
const pixel32 = new Uint32Array(imageData.data.buffer);
pixel32[0] = 0;
// Spray paint logic.
const density = 10;
const radius = 10;
// mouse handler
const mouse = {x : 0, y : 0, button : false};
function mouseEvents(e){
const bounds = canvas.getBoundingClientRect();
mouse.x = e.pageX - bounds.left - scrollX;
mouse.y = e.pageY - bounds.top - scrollY;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
["down","up","move"].forEach(name => document.addEventListener("mouse"+name,mouseEvents));
function getRandomOffset() {
const angle = Math.random() * Math.PI * 2;
const rad = Math.random() * radius;
return { x: Math.cos(angle) * rad, y: Math.sin(angle) * rad};
}
function spray(pos) {
var i;
for (i = 0; i < density; i++) {
const offset = getRandomOffset();
ctx.putImageData(imageData, pos.x + offset.x, pos.y + offset.y);
}
}
// main loop called 60 times a second
function mainLoop(){
if (mouse.button) { spray(mouse) }
requestAnimationFrame(mainLoop);
}
<canvas id="canvas" width="800" height="554"></canvas>

Related

Enable to scale a ImageData from a CanvasRenderingContext2D into a other one

Here I have my main canvas 2D context that is on my screen named baseCtx that is in the custom service drawingService.
zoomCtx is the CanvasRenderingContext2D of my second canvas and zoomCanvas is the HTMLCanvasElement of my secondary canvas.
I want to take a rectangle that is the size of a smaller canvas that have for center my mouse.
CurrentX and CurrentY are the current mousePosition on my main canvas.
That is working just fine I can see the content of the rectangle zone on the secondary canvas.
The problem come when I try to zoom in the secondary canvas that will play the role of a magnifying glass. I can see the zone around my cursor drawing on the secondary canvas, it is just not zoom in.
I just won't zoom event tho I am using the scale method.
Here is my code that is called each time the mouse move
calculateZoomedPixel() {
let sx = this.currentX - this.zoomCanvas.width / 2;
let sy = this.currentY - this.zoomCanvas.height / 2;
const zoom = 2;
let image = this.drawingService.baseCtx.getImageData(sx, sy, this.zoomCanvas.width, this.zoomCanvas.height);
this.zoomCtx.putImageData(image, 0, 0);
this.zoomCtx.translate(zoom * this.zoomCanvas.width, zoom * this.zoomCanvas.height);
this.zoomCtx.scale(zoom, zoom);
this.zoomCtx.drawImage(this.zoomCanvas, 0, 0);
this.zoomCtx.translate(-zoom * this.zoomCanvas.width, -zoom * this.zoomCanvas.height);
}
Here is an example of what i want the second canvas to look like:
And here is an example of my application (The smaller canvas to the left should be zoom in):
A few problems here:
Your translate calls are not made properly, you are only translating back after you drew the image, which has no good effect.
You never reset the transformation matrix after you set its scale, so at second call, your zoom canvas as its scale set to 4, at third, to 8 etc.
To workaround both these problems, you can use the absolute setTransform() method to set both the scale and the translate in one call, and then translate back using the drawImage's parameters:
const source_width = source.width = 500;
const source_height = source.height = 500;
const mag_width = magnifier.width = 100;
const mag_height = magnifier.height = 100;
const source_ctx = source.getContext("2d");
source_ctx.fillStyle = "white";
source_ctx.fillRect(0, 0, source_width, source_height);
source_ctx.stroke(randomLines());
const mag_ctx = magnifier.getContext("2d");
mag_ctx.imageSmoothingEnabled = false;
mag_ctx.globalCompositeOperation = "copy";
source.onmousemove = (evt) => {
const rect = source.getBoundingClientRect();
const current_x = evt.clientX - rect.left;
const current_y = evt.clientY - rect.top;
const sx = current_x - mag_width / 2;
const sy = current_y - mag_height / 2;
const zoom = 10;
const image = source_ctx.getImageData(sx, sy, mag_width, mag_height);
mag_ctx.putImageData(image, 0, 0);
// set the zoom and translate to center in one call
mag_ctx.setTransform(zoom, 0, 0, zoom, mag_width/2, mag_height/2 );
// translate back in drawImage to center our image
mag_ctx.drawImage(magnifier, -mag_width/2, -mag_height/2);
// reset to identity matrix
mag_ctx.setTransform(1, 0, 0, 1, 0, 0);
};
function randomLines() {
const path = new Path2D();
for( let i = 0; i<30; i++ ) {
const x = Math.random() * source_width;
const y = Math.random() * source_height;
path.lineTo(x, y);
}
return path;
}
#magnifier { position: absolute; border: 1px solid; }
<canvas id="magnifier"></canvas>
<canvas id="source"></canvas>
But you should not call getImageData in a mousemove event like this. getImageData is utterly slow as it requires to move the context's buffer from the GPU to the CPU. Call it only once to grab the full canvas and reuse only that single ImageData:
const source_width = source.width = 500;
const source_height = source.height = 500;
const mag_width = magnifier.width = 100;
const mag_height = magnifier.height = 100;
const source_ctx = source.getContext("2d");
source_ctx.fillStyle = "white";
source_ctx.fillRect(0, 0, source_width, source_height);
source_ctx.stroke(randomLines());
const mag_ctx = magnifier.getContext("2d");
mag_ctx.imageSmoothingEnabled = false;
// get the image data only once, when the drawing is done
const image = source_ctx.getImageData(0, 0, source_width, source_height );
source.onmousemove = (evt) => {
mag_ctx.clearRect(0, 0, mag_width, mag_height);
const rect = source.getBoundingClientRect();
const current_x = evt.clientX - rect.left;
const current_y = evt.clientY - rect.top;
const sx = current_x - mag_width / 2;
const sy = current_y - mag_height / 2;
const zoom = 10;
// draw the correct portion of the ImageData
mag_ctx.putImageData(image, -sx, -sy, sx, sy, source_width, source_height);
// set the zoom and translate to center in one call
mag_ctx.setTransform(zoom, 0, 0, zoom, mag_width/2, mag_height/2 );
// translate back in drawImage to center our image
mag_ctx.drawImage(magnifier, -mag_width/2, -mag_height/2);
// reset to identity matrix
mag_ctx.setTransform(1, 0, 0, 1, 0, 0);
};
function randomLines() {
const path = new Path2D();
for( let i = 0; i<30; i++ ) {
const x = Math.random() * source_width;
const y = Math.random() * source_height;
path.lineTo(x, y);
}
return path;
}
#magnifier { position: absolute; border: 1px solid; }
<canvas id="magnifier"></canvas>
<canvas id="source"></canvas>
And if you are not doing anything with these pixels' data, then just use drawImage directly:
const source_width = source.width = 500;
const source_height = source.height = 500;
const mag_width = magnifier.width = 100;
const mag_height = magnifier.height = 100;
const source_ctx = source.getContext("2d");
source_ctx.fillStyle = "white";
source_ctx.fillRect(0, 0, source_width, source_height);
source_ctx.stroke(randomLines());
const mag_ctx = magnifier.getContext("2d");
mag_ctx.imageSmoothingEnabled = false;
source.onmousemove = (evt) => {
mag_ctx.clearRect(0, 0, mag_width, mag_height);
const rect = source.getBoundingClientRect();
const current_x = evt.clientX - rect.left;
const current_y = evt.clientY - rect.top;
const sx = current_x - mag_width / 2;
const sy = current_y - mag_height / 2;
const zoom = 10;
mag_ctx.setTransform(zoom, 0, 0, zoom, mag_width/2, mag_height/2 );
// draw source canvas directly
mag_ctx.drawImage(source, sx, sy, mag_width, mag_height, -mag_width/2, -mag_height/2, mag_width, mag_height);
// reset to identity matrix
mag_ctx.setTransform(1, 0, 0, 1, 0, 0);
};
function randomLines() {
const path = new Path2D();
for( let i = 0; i<30; i++ ) {
const x = Math.random() * source_width;
const y = Math.random() * source_height;
path.lineTo(x, y);
}
return path;
}
#magnifier { position: absolute; border: 1px solid; }
<canvas id="magnifier"></canvas>
<canvas id="source"></canvas>

HTML Canvas get total fill in percent

I doing a canvas to restore the original image when cursor moving around, in different percentage to show in different message to tell user. How to calculate the total percentage that already filled?
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
context.beginPath();
context.fillStyle = 'black';
context.fillRect(0, 0, 400, 300);
canvas.onmousedown = function() {
canvas.onmousemove = function() {
var x = event.clientX;
var y = event.clientY;
context.globalCompositeOperation = "destination-out";
context.beginPath();
context.arc(x-0, y, 30, 0, Math.PI*2);
context.fill();
}
}
canvas.onmouseup = function() {
canvas.onmousemove = function() {
//
}
}
<img src="http://blog.honeyfeed.fm/wp-content/uploads/2015/01/onepiece-wallpaper-20160724205402-560x380.jpg" style="width: 400px; height: 300px; position: absolute; z-index: -1;" />
<canvas id="canvas" width="400" height="300"></canvas>
If you want to "brute force" this calculation, you could use getImageData and check the total number of pixels that is transparent.
The main code:
// This returns an array with 4 bytes (0-255) per pixel
// data[0] -> R value of first pixel
// data[1], [2], and [3] -> G, B, and A values
// etc.
const data = context
.getImageData(0, 0, canvas.width, canvas.height)
.data;
// The total number of pixels is the length of the
// data array divided by 4, or width * height
const nrOfPixels = data.length / 4; // rgba pixels
let transparent = 0;
// Your code removes the alpha, so we check each
// 4th item in the array (notice the += 4)
// If it's transparent (A === 0), we count it
for (let i = 3; i < data.length; i += 4) {
transparent += data[i] ? 0 : 1;
}
// The percentage is the number of transparent pixels
// divided by the total number of pixels
const percentage = transparent / nrOfPixels * 100;
This is by no means an optimized way of doing this. That's why, for now, I included it in the mouseup event listener and put a console.time around it.
EDIT: because I felt guilty that I answered a duplicate question with almost the exact same solution as was apparently linked in the comments, I optimized for performance. Now I feel this answer actually adds an additional solution.
The optimization:
We divide our canvas in to a grid of squares size s
One array holds the transparent pixel count per box
Another array holds the top left coordinate for boxes that need recalculation
On every mouse move, we calculate the four corners of a box surrounding our cleared circle
For each corner's x,y location, we check in which of the grid boxes it lies
We mark this grid box as "dirty", which means it has to be checked for changes.
On every mouse move, we use requestAnimationFrame to request a new update calculation
In the update, we do no longer retrieve all image data. Instead, we only request the image data for our dirty grid boxes.
We calculate the transparency for every grid box, add them up and divide by the number of total pixels.
The size of the grid and the size of the brush determine the performance gain of this approach. With the settings in the example below, I was able to get a performance gain of around 400% (4.x ms per calculation to <1ms)
Note that the grid size must be larger than your brush size.
const GRID_SIZE = 50;
const DRAW_SIZE = 30;
var ExposeImage = function(canvas, display) {
const width = canvas.width;
const height = canvas.height;
const cols = width / GRID_SIZE;
const rows = height / GRID_SIZE;
this.gridBlocks = Array(rows * cols);
this.dirtyBlocks = Array(rows * cols);
const gridBlockIndex = (c, r) => r * cols + c;
const rcFromBlockIndex = i => [
Math.floor(i / cols),
i % cols
];
this.context = canvas.getContext("2d");
this.display = display;
this.init();
var logDirtyGridBoxes = function(e) {
var x = e.clientX;
var y = e.clientY;
var r = DRAW_SIZE;
var top = Math.max(y - r, 0);
var bottom = Math.min(y + r, height - 1);
var left = Math.max(x - r, 0);
var right = Math.min(x + r, width - 1);
var corners = [
[top, left],
[top, right],
[bottom, right],
[bottom, left]
];
corners.forEach(c => {
const row = Math.floor(c[0] / GRID_SIZE);
const col = Math.floor(c[1] / GRID_SIZE);
const i = gridBlockIndex(col, row);
this.dirtyBlocks[i] =
/* top left of the grid block */
[col * GRID_SIZE, row * GRID_SIZE];
});
}.bind(this);
var update = function() {
console.time("update");
// Store the transparent pixel count for all our dirty
// grid boxes
this.dirtyBlocks.forEach((coords, i) => {
const data = this.context.getImageData(
coords[0], coords[1], GRID_SIZE, GRID_SIZE).data;
this.gridBlocks[i] = transparentPixelCount(data)
})
// Clear dirty array
this.dirtyBlocks = Array(rows * cols);
// Calculate total average
const total = this.gridBlocks.reduce((sum, b) => sum + b, 0);
const avg = Math.round(
total / (width * height) * 100);
console.timeEnd("update");
display.innerText = avg + "%";
}.bind(this);
// Event listeners
var onMove = function(e) {
this.clear(e.clientX, e.clientY, DRAW_SIZE);
logDirtyGridBoxes(e);
requestAnimationFrame(update);
}.bind(this);
canvas.addEventListener("mousedown", function(e) {
canvas.addEventListener("mousemove", onMove);
onMove(e);
}.bind(this));
canvas.addEventListener("mouseup", function() {
canvas.removeEventListener("mousemove", onMove);
}.bind(this));
};
ExposeImage.prototype.init = function(context) {
this.context.beginPath();
this.context.fillStyle = 'black';
this.context.fillRect(0, 0, 400, 300);
this.context.globalCompositeOperation = "destination-out";
};
ExposeImage.prototype.clear = function(x, y, r) {
this.context.beginPath();
this.context.arc(x - 0, y, r, 0, Math.PI * 2);
this.context.fill();
};
// App:
var canvas = document.getElementById("canvas");
var display = document.querySelector(".js-display");
var ei = new ExposeImage(canvas, display);
function transparentPixelCount(data) {
let transparent = 0;
for (let i = 3; i < data.length; i += 4) {
transparent += data[i] ? 0 : 1;
}
return transparent;
}
<img src="http://blog.honeyfeed.fm/wp-content/uploads/2015/01/onepiece-wallpaper-20160724205402-560x380.jpg" style="width: 400px; height: 300px; position: absolute; z-index: -1;" />
<canvas id="canvas" width="400" height="300"></canvas>
<div class="js-display">0%</div>

HTML5 Canvas: Bouncing Balls with Image Overlay

I'm really struggling with a couple problems in the HTML5 canvas.
I've posted the project to GitHub pages (https://swedy13.github.io/) and added an image (the circles are in motion) so you can see the issue. Basically, if you scroll down you'll find several green circles bouncing around on the page. I'd like to replace those with my client logos.
I'm calling requestAnimation from three files based on different actions, all of which can be found in https://github.com/swedy13/swedy13.github.io/tree/master/assets/js
Filenames:
- filters.js (calls requestAnimation when you use the filters)
- main.js (on load and resize)
- portfolio.js (this is where the canvas code is)
Update: I've added the "portfolio.js" code below so the answer can be self-contained.
function runAnimation(width, height, type){
var canvas = document.getElementsByTagName('canvas')[0];
var c = canvas.getContext('2d');
// ---- DIMENSIONS ---- //
// Container
var x = width;
var y = height - 65;
canvas.width = x;
canvas.height = y;
var container = {x: 0 ,y: 0 ,width: x, height: y};
// Portrait Variables
var cPos = 200;
var cMargin = 70;
var cSpeed = 3;
var r = x*.075;
if (y > x && x >= 500) {
cPos = x * (x / y) - 150;
cMargin = 150;
}
// Landscape Variables
if (x > y) {
cPos = y * (y / x) - 50;
cMargin = 150;
cSpeed = 3;
r = x*.05;
}
// ---- CIRCLES ---- //
// Circles
var circles = [];
var img = new Image();
// Gets active post ids and count
var activeName = [];
var activeLogo = [];
var activePosts = $('.active').map(function() {
activeName.push($(this).text().replace(/\s+/g, '-').toLowerCase());
// Returns the image source
/*activeLogo.push($(this).find('img').prop('src'));*/
// Returns an image node
var elem = document.getElementsByClassName($(this).text().replace(/\s+/g, '-').toLowerCase())
activeLogo.push(elem[0].childNodes[0]);
});
// Populates circle data
for (var i = 0; i < $('.active').length; i++) {
circles.push({
id:activeName[i],
r:r,
color: 100,
/*image: activeLogo[i],*/
x:Math.random() * cPos + cMargin,
y:Math.random() * cPos + cMargin,
vx:Math.random() * cSpeed + .25,
vy:Math.random() * cSpeed + .25
});
}
// ---- DRAW ---- //
requestAnimationFrame(draw);
function draw(){
c.fillStyle = 'white';
c.fillRect(container.x, container.y, container.width, container.height);
for (var i = 0; i < circles.length; i++){
/*var img = new Image();
var path = circles[i].image;*/
/*var size = circles[i].r * 2;*/
/*img.src = circles[4].image;*/
var img = activeLogo[i];
img.onload = function (circles) {
/*c.drawImage(img, 0, 0, size, size);*/
var pattern = c.createPattern(this, "repeat");
c.fillStyle = pattern;
c.fill();
};
c.fillStyle = 'hsl(' + circles[i].color + ', 100%, 50%)';
c.beginPath();
c.arc(circles[i].x, circles[i].y, circles[i].r, 0, 2*Math.PI, false);
c.fill();
// If the circle size/position is greater than the canvas width, bounce x
if ((circles[i].x + circles[i].vx + circles[i].r > container.width) || (circles[i].x - circles[i].r + circles[i].vx < container.x)) {
circles[i].vx = -circles[i].vx;
}
// If the circle size/position is greater than the canvas width, bounce y
if ((circles[i].y + circles[i].vy + circles[i].r > container.height) || (circles[i].y - circles[i].r + circles[i].vy < container.y)){
circles[i].vy = -circles[i].vy;
}
// Generates circle motion by adding position and velocity each frame
circles[i].x += circles[i].vx;
circles[i].y += circles[i].vy;
}
requestAnimationFrame(draw);
}
}
The way it works right now is:
1. I have my portfolio content set to "display: none" (eventually it will be a pop-up when they click on one of the circles).
2. The canvas is getting the portfolio objects from the DOM, including the image that I can't get to work.
3. If I use the "onload()" function, I can get the images to show up and repeat in the background. But it's just a static background - the circles are moving above it and revealing the background. That isn't what I want.
So basically, I'm trying to figure out how to attach the background image to the circle (based on the circle ID).
----------------- UPDATE -----------------
I can now clip the image to a circle and get the circle to move in the background. But it isn't visible on the page (I can tell it's moving by console logging it's position). The only time I see anything is when the circle lines up with the images position, then it shows.
function runAnimation(width, height, type){
var canvas = document.getElementsByTagName('canvas')[0];
var c = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
// Collects portfolio information from the DOM
var activeName = [];
var activeLogo = [];
$('.active').map(function() {
var text = $(this).text().replace(/\s+/g, '-').toLowerCase();
var elem = document.getElementsByClassName(text);
activeName.push(text);
activeLogo.push(elem[0].childNodes[0]);
});
var img = new Image();
img.onload = start;
var circles = [];
var cPos = 200;
var cMargin = 70;
var cSpeed = 3;
for (var i = 0; i < 1; i++) {
circles.push({
id: activeName[i],
img: activeLogo[i],
size: 50,
xPos: Math.random() * cPos + cMargin,
yPos: Math.random() * cPos + cMargin,
xVel: Math.random() * cSpeed + .25,
yVel: Math.random() * cSpeed + .25,
});
img.src = circles[i].img;
}
requestAnimationFrame(start);
function start(){
for (var i = 0; i < circles.length; i++) {
var circle = createImageInCircle(circles[i].img, circles[i].size, circles[i].xPos, circles[i].yPos);
c.drawImage(circle, circles[i].size, circles[i].size);
animateCircle(circles[i]);
}
requestAnimationFrame(start);
}
function createImageInCircle(img, radius, x, y){
var canvas2 = document.createElement('canvas');
var c2 = canvas2.getContext('2d');
canvas2.width = canvas2.height = radius*2;
c2.fillStyle = 'white';
c2.beginPath();
c2.arc(x, y, radius, 0, Math.PI*2);
c2.fill();
c2.globalCompositeOperation = 'source-atop';
c2.drawImage(img, 0, 0, 100, 100);
return(canvas2);
}
function animateCircle(circle) {
// If the circle size/position is greater than the canvas width, bounce x
if ((circle.xPos + circle.xVel + circle.size > canvas.width) || (circle.xPos - circle.size + circle.xVel < 0)) {
console.log('Bounce X');
circle.xVel = -circle.xVel;
}
// If the circle size/position is greater than the canvas width, bounce y
if ((circle.yPos + circle.yVel + circle.size > canvas.height) || (circle.yPos + circle.yVel - circle.size < 0)) {
console.log('Bounce Y');
circle.yVel = -circle.yVel;
}
// Generates circle motion by adding position and velocity each frame
circle.xPos += circle.xVel;
circle.yPos += circle.yVel;
}
}
I'm not sure if I'm animating the correct thing. I've tried animating canvas2, but that didn't make sense to me.
PS - Sorry for the GitHub formatting, not sure why it looks like that.
PPS - Apologies for any junk code I didn't clean up. I've tried a lot of stuff and probably lost track of some of the changes.
PPPS - And forgive me for not making the answer self-contained. I thought linking to GitHub would be more useful, but I've updated the question to contain all the necessary info. Thanks for the feedback.
To get you started...
Here's how to clip an image into a circle using compositing.
The example code creates a single canvas logo-ball that you can reuse for each of your bouncing balls.
var logoball1=dreateImageInCircle(logoImg1,50);
var logoball2=dreateImageInCircle(logoImg2,50);
Then you can draw each logo-ball onto your main canvas like this:
ctx.drawImage(logoball1,35,40);
ctx.drawImage(logoball2,100,75);
There are many examples here on Stackoverflow of how to animate the balls around the canvas so I leave that part to you.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/m%26m600x455.jpg";
function start(){
var copy=createImageInCircle(img,50);
ctx.drawImage(copy,20,75);
ctx.drawImage(copy,150,120);
ctx.drawImage(copy,280,75);
}
function createImageInCircle(img,radius){
var c=document.createElement('canvas');
var cctx=c.getContext('2d');
c.width=c.height=radius*2;
cctx.beginPath();
cctx.arc(radius,radius,radius,0,Math.PI*2);
cctx.fill();
cctx.globalCompositeOperation='source-atop';
cctx.drawImage(img,radius-img.width/2,radius-img.height/2);
return(c);
}
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=512 height=512></canvas>

Canvas - Draw only when hovering over new tile instead of whole canvas

Let's say I have a canvas that is split into a 15x10 32-pixel checkboard. Thus, I have this:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var tileSize = 32;
var xCoord
var yCoord
var tilesX = 15; // tiles across
var tilesY = 10; // tiles up and down
var counted = 1; // for drawing purpose for checkerboard for visual guidance
var mouseSel = new Image()
mouseSel.src = 'http://i.imgur.com/vAA03NB.png' // mouse selection
mouseSel.width = 32
mouseSel.height = 32
function isOdd(num) {
return num % 2;
}
function getMousePos(canvas, evt) {
// super simple stuff here
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
drawCanvas(); // upon intilization... draw
function drawCanvas() {
for (var y = 0; y <= 10; y++) {
for (var x = 0; x <= 15; x++) {
if (isOdd(counted)) {
context.fillStyle = '#dedede'
context.fillRect(x * 32, y * 32, 32, 32);
// checkboard drawn complete.
}
counted++;
} // end first foor loop
counted++;
} // end last for loop
if (counted >= 176) counted = 1 // once all tiles (16x11) are drawn... reset counter for next instance
}
canvas.addEventListener('mousemove', function (evt) {
context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas so mouse isn't stuck
drawCanvas(); // draw checkboard
// get the actual x,y position of 15x10 32-pixel checkboard
var mousePos = getMousePos(canvas, evt);
mousePos.xCoord = Math.floor(mousePos.x / tileSize)
mousePos.yCoord = Math.floor(mousePos.y / tileSize)
// draw the mouse selection
context.drawImage(mouseSel, (mousePos.xCoord * 32), (mousePos.yCoord * 32), 32, 32) // draw mouse selection
// debug
var message = ' (' + mousePos.xCoord + ',' + mousePos.yCoord + ') | (' + mousePos.x + ',' + mousePos.y + ')';
var textarea = document.getElementById('debug');
textarea.scrollTop = textarea.scrollHeight;
$('#debug').append(message + '\n');
}, false);
canvas#canvas {
background: #ABABAB;
position: relative;
z-index: 1;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" height="352" width="512" tabindex="0"></canvas>
<textarea name="" id="debug" cols="30" rows="35"></textarea>
**NOTE: ** Make sure to scroll down in that preview pane so you can see the debug textarea.
As you can see, the event of "drawing" fires EVERY single time it moves. That means every pixel.
I am trying to figure out how to make the drawing fire ONLY when a new x,y coord has changed. Because it'd be useless to redraw the mouse selection when it's only moved 5 pixels across and it's still going to be drawn at the same place.
My suggestion
Upon entering, have a temporary value and when that is passed, to redraw again?
Make a temporary value and update that if it was different from before. Then put the code in an if statement where either have changed.
var tempX, tempY;
var newX = 100;
var newY = 100;
tempX = mousePos.xCoord;
tempY = mousePos.yCoord;
if (newX !== tempX || newY !== tempY) {
// code here
}
if (tempX !== newX) newX = mousePos.xCoord;
if (tempY !== newY) newY = mousePos.yCoord;
JSFiddle: http://jsfiddle.net/weka/bvnma354/8/

HTML5 Canvas camera/viewport - how to actually do it?

I'm sure this was solven 1000 times before: I got a canvas in the size of 960*560 and a room in the size of 5000*3000 of which always only 960*560 should be drawn, depending on where the player is. The player should be always in the middle, but when near to borders - then the best view should be calculated). The player can move entirely free with WASD or the arrow keys. And all objects should move themselves - instead of that i move everything else but the player to create the illusion that the player moves.
I now found those two quesitons:
HTML5 - Creating a viewport for canvas works, but only for this type of game, i can't reproduce the code for mine.
Changing the view "center" of an html5 canvas seems to be more promising and also perfomant, but i only understand it for drawing all other objects correctly relative to the player and not how to scroll the canvas viewport relative to the player, which i want to achieve first of course.
My code (simplified - the game logic is seperately):
var canvas = document.getElementById("game");
canvas.tabIndex = 0;
canvas.focus();
var cc = canvas.getContext("2d");
// Define viewports for scrolling inside the canvas
/* Viewport x position */ view_xview = 0;
/* Viewport y position */ view_yview = 0;
/* Viewport width */ view_wview = 960;
/* Viewport height */ view_hview = 560;
/* Sector width */ room_width = 5000;
/* Sector height */ room_height = 3000;
canvas.width = view_wview;
canvas.height = view_hview;
function draw()
{
clear();
requestAnimFrame(draw);
// World's end and viewport
if (player.x < 20) player.x = 20;
if (player.y < 20) player.y = 20;
if (player.x > room_width-20) player.x = room_width-20;
if (player.y > room_height-20) player.y = room_height-20;
if (player.x > view_wview/2) ... ?
if (player.y > view_hview/2) ... ?
}
The way i am trying to get it working feels totally wrong and i don't even know how i am trying it... Any ideas? What do you think about the context.transform-thing?
I hope you understand my description and that someone has an idea. Kind regards
LIVE DEMO at jsfiddle.net
This demo illustrates the viewport usage in a real game scenario. Use arrows keys to move the player over the room. The large room is generated on the fly using rectangles and the result is saved into an image.
Notice that the player is always in the middle except when near to borders (as you desire).
Now I'll try to explain the main portions of the code, at least the parts that are more difficult to understand just looking at it.
Using drawImage to draw large images according to viewport position
A variant of the drawImage method has eight new parameters. We can use this method to slice parts of a source image and draw them to the canvas.
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
The first parameter image, just as with the other variants, is either a reference to an image object or a reference to a different canvas element. For the other eight parameters it's best to look at the image below. The first four parameters define the location and size of the slice on the source image. The last four parameters define the position and size on the destination canvas.
Font: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images
How it works in demo:
We have a large image that represents the room and we want to show on canvas only the part within the viewport. The crop position (sx, sy) is the same position of the camera (xView, yView) and the crop dimensions are the same as the viewport(canvas) so sWidth=canvas.width and sHeight=canvas.height.
We need to take care about the crop dimensions because drawImage draws nothing on canvas if the crop position or crop dimensions based on position are invalid. That's why we need the if sections bellow.
var sx, sy, dx, dy;
var sWidth, sHeight, dWidth, dHeight;
// offset point to crop the image
sx = xView;
sy = yView;
// dimensions of cropped image
sWidth = context.canvas.width;
sHeight = context.canvas.height;
// if cropped image is smaller than canvas we need to change the source dimensions
if(image.width - sx < sWidth){
sWidth = image.width - sx;
}
if(image.height - sy < sHeight){
sHeight = image.height - sy;
}
// location on canvas to draw the croped image
dx = 0;
dy = 0;
// match destination with source to not scale the image
dWidth = sWidth;
dHeight = sHeight;
// draw the cropped image
context.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
Drawing game objects related to viewport
When writing a game it's a good practice separate the logic and the rendering for each object in game. So in demo we have update and draw functions. The update method changes object status like position on the "game world", apply physics, animation state, etc. The draw method actually render the object and to render it properly considering the viewport, the object need to know the render context and the viewport properties.
Notice that game objects are updated considering the game world's position. That means the (x,y) position of the object is the position in world. Despite of that, since the viewport is changing, objects need to be rendered properly and the render position will be different than world's position.
The conversion is simple:
object position in world(room): (x, y)
viewport position: (xView, yView)
render position: (x-xView, y-yView)
This works for all kind of coordinates, even the negative ones.
Game Camera
Our game objects have a separated update method. In Demo implementation, the camera is treated as a game object and also have a separated update method.
The camera object holds the left top position of viewport (xView, yView), an object to be followed, a rectangle representing the viewport, a rectangle that represents the game world's boundary and the minimal distance of each border that player could be before camera starts move (xDeadZone, yDeadZone). Also we defined the camera's degrees of freedom (axis). For top view style games, like RPG, the camera is allowed to move in both x(horizontal) and y(vertical) axis.
To keep player in the middle of viewport we set the deadZone of each axis to converge with the center of canvas. Look at the follow function in the code:
camera.follow(player, canvas.width/2, canvas.height/2)
Note: See the UPDATE section below as this will not produce the expected behavior when any dimension of the map (room) is smaller than canvas.
World's limits
Since each object, including camera, have its own update function, its easy to check the game world's boundary. Only remember to put the code that block the movement at the final of the update function.
Demonstration
See the full code and try it yourself. Most parts of the code have comments that guide you through. I'll assume that you know the basics of Javascript and how to work with prototypes (sometimes I use the term "class" for a prototype object just because it have a similar behavior of a Class in languages like Java).
LIVE DEMO
Full code:
<!DOCTYPE HTML>
<html>
<body>
<canvas id="gameCanvas" width=400 height=400 />
<script>
// wrapper for our game "classes", "methods" and "objects"
window.Game = {};
// wrapper for "class" Rectangle
(function() {
function Rectangle(left, top, width, height) {
this.left = left || 0;
this.top = top || 0;
this.width = width || 0;
this.height = height || 0;
this.right = this.left + this.width;
this.bottom = this.top + this.height;
}
Rectangle.prototype.set = function(left, top, /*optional*/ width, /*optional*/ height) {
this.left = left;
this.top = top;
this.width = width || this.width;
this.height = height || this.height
this.right = (this.left + this.width);
this.bottom = (this.top + this.height);
}
Rectangle.prototype.within = function(r) {
return (r.left <= this.left &&
r.right >= this.right &&
r.top <= this.top &&
r.bottom >= this.bottom);
}
Rectangle.prototype.overlaps = function(r) {
return (this.left < r.right &&
r.left < this.right &&
this.top < r.bottom &&
r.top < this.bottom);
}
// add "class" Rectangle to our Game object
Game.Rectangle = Rectangle;
})();
// wrapper for "class" Camera (avoid global objects)
(function() {
// possibles axis to move the camera
var AXIS = {
NONE: 1,
HORIZONTAL: 2,
VERTICAL: 3,
BOTH: 4
};
// Camera constructor
function Camera(xView, yView, viewportWidth, viewportHeight, worldWidth, worldHeight) {
// position of camera (left-top coordinate)
this.xView = xView || 0;
this.yView = yView || 0;
// distance from followed object to border before camera starts move
this.xDeadZone = 0; // min distance to horizontal borders
this.yDeadZone = 0; // min distance to vertical borders
// viewport dimensions
this.wView = viewportWidth;
this.hView = viewportHeight;
// allow camera to move in vertical and horizontal axis
this.axis = AXIS.BOTH;
// object that should be followed
this.followed = null;
// rectangle that represents the viewport
this.viewportRect = new Game.Rectangle(this.xView, this.yView, this.wView, this.hView);
// rectangle that represents the world's boundary (room's boundary)
this.worldRect = new Game.Rectangle(0, 0, worldWidth, worldHeight);
}
// gameObject needs to have "x" and "y" properties (as world(or room) position)
Camera.prototype.follow = function(gameObject, xDeadZone, yDeadZone) {
this.followed = gameObject;
this.xDeadZone = xDeadZone;
this.yDeadZone = yDeadZone;
}
Camera.prototype.update = function() {
// keep following the player (or other desired object)
if (this.followed != null) {
if (this.axis == AXIS.HORIZONTAL || this.axis == AXIS.BOTH) {
// moves camera on horizontal axis based on followed object position
if (this.followed.x - this.xView + this.xDeadZone > this.wView)
this.xView = this.followed.x - (this.wView - this.xDeadZone);
else if (this.followed.x - this.xDeadZone < this.xView)
this.xView = this.followed.x - this.xDeadZone;
}
if (this.axis == AXIS.VERTICAL || this.axis == AXIS.BOTH) {
// moves camera on vertical axis based on followed object position
if (this.followed.y - this.yView + this.yDeadZone > this.hView)
this.yView = this.followed.y - (this.hView - this.yDeadZone);
else if (this.followed.y - this.yDeadZone < this.yView)
this.yView = this.followed.y - this.yDeadZone;
}
}
// update viewportRect
this.viewportRect.set(this.xView, this.yView);
// don't let camera leaves the world's boundary
if (!this.viewportRect.within(this.worldRect)) {
if (this.viewportRect.left < this.worldRect.left)
this.xView = this.worldRect.left;
if (this.viewportRect.top < this.worldRect.top)
this.yView = this.worldRect.top;
if (this.viewportRect.right > this.worldRect.right)
this.xView = this.worldRect.right - this.wView;
if (this.viewportRect.bottom > this.worldRect.bottom)
this.yView = this.worldRect.bottom - this.hView;
}
}
// add "class" Camera to our Game object
Game.Camera = Camera;
})();
// wrapper for "class" Player
(function() {
function Player(x, y) {
// (x, y) = center of object
// ATTENTION:
// it represents the player position on the world(room), not the canvas position
this.x = x;
this.y = y;
// move speed in pixels per second
this.speed = 200;
// render properties
this.width = 50;
this.height = 50;
}
Player.prototype.update = function(step, worldWidth, worldHeight) {
// parameter step is the time between frames ( in seconds )
// check controls and move the player accordingly
if (Game.controls.left)
this.x -= this.speed * step;
if (Game.controls.up)
this.y -= this.speed * step;
if (Game.controls.right)
this.x += this.speed * step;
if (Game.controls.down)
this.y += this.speed * step;
// don't let player leaves the world's boundary
if (this.x - this.width / 2 < 0) {
this.x = this.width / 2;
}
if (this.y - this.height / 2 < 0) {
this.y = this.height / 2;
}
if (this.x + this.width / 2 > worldWidth) {
this.x = worldWidth - this.width / 2;
}
if (this.y + this.height / 2 > worldHeight) {
this.y = worldHeight - this.height / 2;
}
}
Player.prototype.draw = function(context, xView, yView) {
// draw a simple rectangle shape as our player model
context.save();
context.fillStyle = "black";
// before draw we need to convert player world's position to canvas position
context.fillRect((this.x - this.width / 2) - xView, (this.y - this.height / 2) - yView, this.width, this.height);
context.restore();
}
// add "class" Player to our Game object
Game.Player = Player;
})();
// wrapper for "class" Map
(function() {
function Map(width, height) {
// map dimensions
this.width = width;
this.height = height;
// map texture
this.image = null;
}
// creates a prodedural generated map (you can use an image instead)
Map.prototype.generate = function() {
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = this.width;
ctx.canvas.height = this.height;
var rows = ~~(this.width / 44) + 1;
var columns = ~~(this.height / 44) + 1;
var color = "red";
ctx.save();
ctx.fillStyle = "red";
for (var x = 0, i = 0; i < rows; x += 44, i++) {
ctx.beginPath();
for (var y = 0, j = 0; j < columns; y += 44, j++) {
ctx.rect(x, y, 40, 40);
}
color = (color == "red" ? "blue" : "red");
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
ctx.restore();
// store the generate map as this image texture
this.image = new Image();
this.image.src = ctx.canvas.toDataURL("image/png");
// clear context
ctx = null;
}
// draw the map adjusted to camera
Map.prototype.draw = function(context, xView, yView) {
// easiest way: draw the entire map changing only the destination coordinate in canvas
// canvas will cull the image by itself (no performance gaps -> in hardware accelerated environments, at least)
/*context.drawImage(this.image, 0, 0, this.image.width, this.image.height, -xView, -yView, this.image.width, this.image.height);*/
// didactic way ( "s" is for "source" and "d" is for "destination" in the variable names):
var sx, sy, dx, dy;
var sWidth, sHeight, dWidth, dHeight;
// offset point to crop the image
sx = xView;
sy = yView;
// dimensions of cropped image
sWidth = context.canvas.width;
sHeight = context.canvas.height;
// if cropped image is smaller than canvas we need to change the source dimensions
if (this.image.width - sx < sWidth) {
sWidth = this.image.width - sx;
}
if (this.image.height - sy < sHeight) {
sHeight = this.image.height - sy;
}
// location on canvas to draw the croped image
dx = 0;
dy = 0;
// match destination with source to not scale the image
dWidth = sWidth;
dHeight = sHeight;
context.drawImage(this.image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
}
// add "class" Map to our Game object
Game.Map = Map;
})();
// Game Script
(function() {
// prepaire our game canvas
var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");
// game settings:
var FPS = 30;
var INTERVAL = 1000 / FPS; // milliseconds
var STEP = INTERVAL / 1000 // seconds
// setup an object that represents the room
var room = {
width: 500,
height: 300,
map: new Game.Map(500, 300)
};
// generate a large image texture for the room
room.map.generate();
// setup player
var player = new Game.Player(50, 50);
// Old camera setup. It not works with maps smaller than canvas. Keeping the code deactivated here as reference.
/* var camera = new Game.Camera(0, 0, canvas.width, canvas.height, room.width, room.height);*/
/* camera.follow(player, canvas.width / 2, canvas.height / 2); */
// Set the right viewport size for the camera
var vWidth = Math.min(room.width, canvas.width);
var vHeight = Math.min(room.height, canvas.height);
// Setup the camera
var camera = new Game.Camera(0, 0, vWidth, vHeight, room.width, room.height);
camera.follow(player, vWidth / 2, vHeight / 2);
// Game update function
var update = function() {
player.update(STEP, room.width, room.height);
camera.update();
}
// Game draw function
var draw = function() {
// clear the entire canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// redraw all objects
room.map.draw(context, camera.xView, camera.yView);
player.draw(context, camera.xView, camera.yView);
}
// Game Loop
var gameLoop = function() {
update();
draw();
}
// <-- configure play/pause capabilities:
// Using setInterval instead of requestAnimationFrame for better cross browser support,
// but it's easy to change to a requestAnimationFrame polyfill.
var runningId = -1;
Game.play = function() {
if (runningId == -1) {
runningId = setInterval(function() {
gameLoop();
}, INTERVAL);
console.log("play");
}
}
Game.togglePause = function() {
if (runningId == -1) {
Game.play();
} else {
clearInterval(runningId);
runningId = -1;
console.log("paused");
}
}
// -->
})();
// <-- configure Game controls:
Game.controls = {
left: false,
up: false,
right: false,
down: false,
};
window.addEventListener("keydown", function(e) {
switch (e.keyCode) {
case 37: // left arrow
Game.controls.left = true;
break;
case 38: // up arrow
Game.controls.up = true;
break;
case 39: // right arrow
Game.controls.right = true;
break;
case 40: // down arrow
Game.controls.down = true;
break;
}
}, false);
window.addEventListener("keyup", function(e) {
switch (e.keyCode) {
case 37: // left arrow
Game.controls.left = false;
break;
case 38: // up arrow
Game.controls.up = false;
break;
case 39: // right arrow
Game.controls.right = false;
break;
case 40: // down arrow
Game.controls.down = false;
break;
case 80: // key P pauses the game
Game.togglePause();
break;
}
}, false);
// -->
// start the game when page is loaded
window.onload = function() {
Game.play();
}
</script>
</body>
</html>
UPDATE
If width and/or height of the map (room) is smaller than canvas the previous code will not work properly. To resolve this, in the Game Script make the setup of the camera as followed:
// Set the right viewport size for the camera
var vWidth = Math.min(room.width, canvas.width);
var vHeight = Math.min(room.height, canvas.height);
var camera = new Game.Camera(0, 0, vWidth, vHeight, room.width, room.height);
camera.follow(player, vWidth / 2, vHeight / 2);
You just need to tell the camera constructor that viewport will be the smallest value between map (room) or canvas. And since we want the player centered and bonded to that viewport, the camera.follow function must be update as well.
Feel free to report any errors or to add suggestions.
Here is a simple example of this where we clamp the camera position to the bounds of the game world. This allows the camera to move through the game world and will never display any void space outside of the bounds you specify.
const worldBounds = {minX:-100,maxX:100,minY:-100,maxY:100};
function draw() {
ctx.setTransform(1,0,0,1,0,0);//reset the transform matrix as it is cumulative
ctx.clearRect(0, 0, canvas.width, canvas.height);//clear the viewport AFTER the matrix is reset
// update the player position
movePlayer();
// player is clamped to the world boundaries - don't let the player leave
player.x = clamp(player.x, worldBounds.minX, worldBounds.maxX);
player.y = clamp(player.y, worldBounds.minY, worldBounds.maxY);
// center the camera around the player,
// but clamp the edges of the camera view to the world bounds.
const camX = clamp(player.x - canvas.width/2, worldBounds.minX, worldBounds.maxX - canvas.width);
const camY = clamp(player.y - canvas.height/2, worldBounds.minY, worldBounds.maxY - canvas.height);
ctx.translate(-camX, -camY);
//Draw everything
}
And clamp just ensures that the value given is always between the specified min/max range :
// clamp(10, 20, 30) - output: 20
// clamp(40, 20, 30) - output: 30
// clamp(25, 20, 30) - output: 25
function clamp(value, min, max){
if(value < min) return min;
else if(value > max) return max;
return value;
}
Building on #dKorosec's example - use the arrow keys to move:
Fiddle
Here’s how to use canvas to be a viewport on another larger-than-canvas image
A viewport is really just a cropped portion of a larger image that is displayed to the user.
In this case, the viewport will be displayed to the user on a canvas (the canvas is the viewport).
First, code a move function that pans the viewport around the larger image.
This function moves the top/left corner of the viewport by 5px in the specified direction:
function move(direction){
switch (direction){
case "left":
left-=5;
break;
case "up":
top-=5;
break;
case "right":
left+=5;
break;
case "down":
top+=5
break;
}
draw(top,left);
}
The move function calls the draw function.
In draw(), the drawImage function will crop a specified portion of a larger image.
drawImage will also display that “cropped background” to the user on the canvas.
context.clearRect(0,0,game.width,game.height);
context.drawImage(background,cropLeft,cropTop,cropWidth,cropHeight,
0,0,viewWidth,viewHeight);
In this example,
Background is the full background image (usually not displayed but is rather a source for cropping)
cropLeft & cropTop define where on the background image the cropping will begin.
cropWidth & cropHeight define how large a rectangle will be cropped from the background image.
0,0 say that the sub-image that has been cropped from the background will be drawn at 0,0 on the viewport canvas.
viewWidth & viewHeight are the width and height of the viewport canvas
So here is an example of drawImage using numbers.
Let’s say our viewport (= our display canvas) is 150 pixels wide and 100 pixels high.
context.drawImage(background,75,50,150,100,0,0,150,100);
The 75 & 50 say that cropping will start at position x=75/y=50 on the background image.
The 150,100 say that the rectangle to be cropped will be 150 wide and 100 high.
The 0,0,150,100 say that the cropped rectangle image will be displayed using the full size of the viewport canvas.
That’s it for the mechanics of drawing a viewport…just add key-controls!
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/vXqyc/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var game=document.getElementById("game");
var gameCtx=game.getContext("2d");
var left=20;
var top=20;
var background=new Image();
background.onload=function(){
canvas.width=background.width/2;
canvas.height=background.height/2;
gameCtx.fillStyle="red";
gameCtx.strokeStyle="blue";
gameCtx.lineWidth=3;
ctx.fillStyle="red";
ctx.strokeStyle="blue";
ctx.lineWidth=3;
move(top,left);
}
background.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/game.jpg";
function move(direction){
switch (direction){
case "left":
left-=5;
break;
case "up":
top-=5;
break;
case "right":
left+=5;
break;
case "down":
top+=5
break;
}
draw(top,left);
}
function draw(top,left){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(background,0,0,background.width,background.height,0,0,canvas.width,canvas.height);
gameCtx.clearRect(0,0,game.width,game.height);
gameCtx.drawImage(background,left,top,250,150,0,0,250,150);
gameCtx.beginPath();
gameCtx.arc(125,75,10,0,Math.PI*2,false);
gameCtx.closePath();
gameCtx.fill();
gameCtx.stroke();
ctx.beginPath();
ctx.rect(left/2,top/2,125,75);
ctx.stroke();
ctx.beginPath();
ctx.arc(left/2+125/2,top/2+75/2,5,0,Math.PI*2,false);
ctx.stroke();
ctx.fill();
}
$("#moveLeft").click(function(){move("left");});
$("#moveRight").click(function(){move("right");});
$("#moveUp").click(function(){move("up");});
$("#moveDown").click(function(){move("down");});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="game" width=250 height=150></canvas><br>
<canvas id="canvas" width=500 height=300></canvas><br>
<button id="moveLeft">Left</button>
<button id="moveRight">Right</button>
<button id="moveUp">Up</button>
<button id="moveDown">Down</button>
</body>
</html>
#gustavo-carvalho's solution is phenomenal, but it involves extensive calculations and cognitive overhead. #Colton's approach is a step in the right direction; too bad it wasn't elaborated enough in his answer. I took his idea and ran with it to create this CodePen. It achieves exactly what #user2337969 is asking for using context.translate. The beauty is that this doesn't require offsetting any map or player coordinates so drawing them is as easy as using their x and y directly, which is much more straightforward.
Think of the 2D camera as a rectangle that pans inside a larger map. Its top-left corner is at (x, y) coordinates in the map, and its size is that of the canvas, i.e. canvas.width and canvas.height. That means that x can range from 0 to map.width - canvas.width, and y from 0 to map.height - canvas.height (inclusive). These are min and max that we feed into #Colton's clamp method.
To make it work however, I had to flip the sign on x and y since with context.translate, positive values shift the canvas to the right (making an illusion as if the camera pans to the left) and negative - to the left (as if the camera pans to the right).
This is a simple matter of setting the viewport to the target's x and y coordinates, as Colton states, on each frame. Transforms are not necessary but can be used as desired. The basic formula without translation is:
function update() {
// Assign the viewport to follow a target for this frame
var viewportX = canvas.width / 2 - target.x;
var viewportY = canvas.height / 2 - target.y;
// Draw each entity, including the target, relative to the viewport
ctx.fillRect(
entity.x + viewportX,
entity.y + viewportY,
entity.size,
entity.size
);
}
Clamping to the map is an optional second step to keep the viewport within world bounds:
function update() {
// Assign the viewport to follow a target for this frame
var viewportX = canvas.width / 2 - target.x;
var viewportY = canvas.height / 2 - target.y;
// Keep viewport in map bounds
viewportX = clamp(viewportX, canvas.width - map.width, 0);
viewportY = clamp(viewportY, canvas.height - map.height, 0);
// Draw each entity, including the target, relative to the viewport
ctx.fillRect(
entity.x + viewportX,
entity.y + viewportY,
entity.size,
entity.size
);
}
// Restrict n to a range between lo and hi
function clamp(n, lo, hi) {
return n < lo ? lo : n > hi ? hi : n;
}
Below are a few examples of this in action.
Without viewport translation, clamped:
const clamp = (n, lo, hi) => n < lo ? lo : n > hi ? hi : n;
const Ship = function (x, y, angle, size, color) {
this.x = x;
this.y = y;
this.vx = 0;
this.vy = 0;
this.ax = 0;
this.ay = 0;
this.rv = 0;
this.angle = angle;
this.accelerationAmount = 0.05;
this.decelerationAmount = 0.02;
this.friction = 0.9;
this.rotationSpd = 0.01;
this.size = size;
this.radius = size;
this.color = color;
};
Ship.prototype = {
accelerate: function () {
this.ax += this.accelerationAmount;
this.ay += this.accelerationAmount;
},
decelerate: function () {
this.ax -= this.decelerationAmount;
this.ay -= this.decelerationAmount;
},
rotateLeft: function () {
this.rv -= this.rotationSpd;
},
rotateRight: function () {
this.rv += this.rotationSpd;
},
move: function () {
this.angle += this.rv;
this.vx += this.ax;
this.vy += this.ay;
this.x += this.vx * Math.cos(this.angle);
this.y += this.vy * Math.sin(this.angle);
this.ax *= this.friction;
this.ay *= this.friction;
this.vx *= this.friction;
this.vy *= this.friction;
this.rv *= this.friction;
},
draw: function (ctx, viewportX, viewportY) {
ctx.save();
ctx.translate(this.x + viewportX, this.y + viewportY);
ctx.rotate(this.angle);
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(this.size / 1.2, 0);
ctx.stroke();
ctx.fillStyle = this.color;
ctx.fillRect(
this.size / -2,
this.size / -2,
this.size,
this.size
);
ctx.strokeRect(
this.size / -2,
this.size / -2,
this.size,
this.size
);
ctx.restore();
}
};
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
canvas.height = canvas.width = 180;
const map = {
height: canvas.height * 5,
width: canvas.width * 5
};
const ship = new Ship(
canvas.width / 2,
canvas.height / 2,
0,
canvas.width / 10 | 0,
"#fff"
);
const keyCodesToActions = {
38: () => ship.accelerate(),
37: () => ship.rotateLeft(),
39: () => ship.rotateRight(),
40: () => ship.decelerate(),
};
const validKeyCodes = new Set(
Object.keys(keyCodesToActions).map(e => +e)
);
const keysPressed = new Set();
document.addEventListener("keydown", e => {
if (validKeyCodes.has(e.keyCode)) {
e.preventDefault();
keysPressed.add(e.keyCode);
}
});
document.addEventListener("keyup", e => {
if (validKeyCodes.has(e.keyCode)) {
e.preventDefault();
keysPressed.delete(e.keyCode);
}
});
(function update() {
requestAnimationFrame(update);
keysPressed.forEach(k => {
if (k in keyCodesToActions) {
keyCodesToActions[k]();
}
});
ship.move();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
const viewportX = clamp(canvas.width / 2 - ship.x, canvas.width - map.width, 0);
const viewportY = clamp(canvas.height / 2 - ship.y, canvas.height - map.height, 0);
/* draw everything offset by viewportX/Y */
const tileSize = canvas.width / 5;
for (let x = 0; x < map.width; x += tileSize) {
for (let y = 0; y < map.height; y += tileSize) {
const xx = x + viewportX;
const yy = y + viewportY;
// simple culling
if (xx > canvas.width || yy > canvas.height ||
xx < -tileSize || yy < -tileSize) {
continue;
}
const light = (~~(x / tileSize + y / tileSize) & 1) * 5 + 70;
ctx.fillStyle = `hsl(${360 - (x + y) / 10}, 50%, ${light}%)`;
ctx.fillRect(xx, yy, tileSize + 1, tileSize + 1);
}
}
ship.draw(ctx, viewportX, viewportY);
ctx.restore();
})();
body {
margin: 0;
font-family: monospace;
display: flex;
flex-flow: row nowrap;
align-items: center;
}
html, body {
height: 100%;
}
canvas {
background: #eee;
border: 4px solid #222;
}
div {
transform: rotate(-90deg);
background: #222;
color: #fff;
padding: 2px;
}
<div>arrow keys to move</div>
With viewport translation, unclamped:
const Ship = function (x, y, angle, size, color) {
this.x = x;
this.y = y;
this.vx = 0;
this.vy = 0;
this.ax = 0;
this.ay = 0;
this.rv = 0;
this.angle = angle;
this.accelerationAmount = 0.05;
this.decelerationAmount = 0.02;
this.friction = 0.9;
this.rotationSpd = 0.01;
this.size = size;
this.radius = size;
this.color = color;
};
Ship.prototype = {
accelerate: function () {
this.ax += this.accelerationAmount;
this.ay += this.accelerationAmount;
},
decelerate: function () {
this.ax -= this.decelerationAmount;
this.ay -= this.decelerationAmount;
},
rotateLeft: function () {
this.rv -= this.rotationSpd;
},
rotateRight: function () {
this.rv += this.rotationSpd;
},
move: function () {
this.angle += this.rv;
this.vx += this.ax;
this.vy += this.ay;
this.x += this.vx * Math.cos(this.angle);
this.y += this.vy * Math.sin(this.angle);
this.ax *= this.friction;
this.ay *= this.friction;
this.vx *= this.friction;
this.vy *= this.friction;
this.rv *= this.friction;
},
draw: function (ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(this.size / 1.2, 0);
ctx.stroke();
ctx.fillStyle = this.color;
ctx.fillRect(
this.size / -2,
this.size / -2,
this.size,
this.size
);
ctx.strokeRect(
this.size / -2,
this.size / -2,
this.size,
this.size
);
ctx.restore();
}
};
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
canvas.height = canvas.width = 180;
const map = {
height: canvas.height * 5,
width: canvas.width * 5
};
const ship = new Ship(
canvas.width / 2,
canvas.height / 2,
0,
canvas.width / 10 | 0,
"#fff"
);
const keyCodesToActions = {
38: () => ship.accelerate(),
37: () => ship.rotateLeft(),
39: () => ship.rotateRight(),
40: () => ship.decelerate(),
};
const validKeyCodes = new Set(
Object.keys(keyCodesToActions).map(e => +e)
);
const keysPressed = new Set();
document.addEventListener("keydown", e => {
if (validKeyCodes.has(e.keyCode)) {
e.preventDefault();
keysPressed.add(e.keyCode);
}
});
document.addEventListener("keyup", e => {
if (validKeyCodes.has(e.keyCode)) {
e.preventDefault();
keysPressed.delete(e.keyCode);
}
});
(function update() {
requestAnimationFrame(update);
keysPressed.forEach(k => {
if (k in keyCodesToActions) {
keyCodesToActions[k]();
}
});
ship.move();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2 - ship.x, canvas.height / 2 - ship.y);
/* draw everything as normal */
const tileSize = canvas.width / 5;
for (let x = 0; x < map.width; x += tileSize) {
for (let y = 0; y < map.height; y += tileSize) {
// simple culling
if (x > ship.x + canvas.width || y > ship.y + canvas.height ||
x < ship.x - canvas.width || y < ship.y - canvas.height) {
continue;
}
const light = ((x / tileSize + y / tileSize) & 1) * 5 + 70;
ctx.fillStyle = `hsl(${360 - (x + y) / 10}, 50%, ${light}%)`;
ctx.fillRect(x, y, tileSize + 1, tileSize + 1);
}
}
ship.draw(ctx);
ctx.restore();
})();
body {
margin: 0;
font-family: monospace;
display: flex;
flex-flow: row nowrap;
align-items: center;
}
html, body {
height: 100%;
}
canvas {
background: #eee;
border: 4px solid #222;
}
div {
transform: rotate(-90deg);
background: #222;
color: #fff;
padding: 2px;
}
<div>arrow keys to move</div>
If you want to keep the target always facing in one direction and rotate the world, make a few adjustments:
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(target.angle); // adjust to match your world
ctx.translate(-target.x, -target.y);
/* draw everything as normal */
Here's an example of this variant:
const Ship = function (x, y, angle, size, color) {
this.x = x;
this.y = y;
this.vx = 0;
this.vy = 0;
this.ax = 0;
this.ay = 0;
this.rv = 0;
this.angle = angle;
this.accelerationAmount = 0.05;
this.decelerationAmount = 0.02;
this.friction = 0.9;
this.rotationSpd = 0.01;
this.size = size;
this.radius = size;
this.color = color;
};
Ship.prototype = {
accelerate: function () {
this.ax += this.accelerationAmount;
this.ay += this.accelerationAmount;
},
decelerate: function () {
this.ax -= this.decelerationAmount;
this.ay -= this.decelerationAmount;
},
rotateLeft: function () {
this.rv -= this.rotationSpd;
},
rotateRight: function () {
this.rv += this.rotationSpd;
},
move: function () {
this.angle += this.rv;
this.vx += this.ax;
this.vy += this.ay;
this.x += this.vx * Math.cos(this.angle);
this.y += this.vy * Math.sin(this.angle);
this.ax *= this.friction;
this.ay *= this.friction;
this.vx *= this.friction;
this.vy *= this.friction;
this.rv *= this.friction;
},
draw: function (ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(this.size / 1.2, 0);
ctx.stroke();
ctx.fillStyle = this.color;
ctx.fillRect(
this.size / -2,
this.size / -2,
this.size,
this.size
);
ctx.strokeRect(
this.size / -2,
this.size / -2,
this.size,
this.size
);
ctx.restore();
}
};
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
canvas.height = canvas.width = 180;
const map = {
height: canvas.height * 5,
width: canvas.width * 5
};
const ship = new Ship(
canvas.width / 2,
canvas.height / 2,
0,
canvas.width / 10 | 0,
"#fff"
);
const keyCodesToActions = {
38: () => ship.accelerate(),
37: () => ship.rotateLeft(),
39: () => ship.rotateRight(),
40: () => ship.decelerate(),
};
const keysPressed = new Set();
document.addEventListener("keydown", e => {
e.preventDefault();
keysPressed.add(e.keyCode);
});
document.addEventListener("keyup", e => {
e.preventDefault();
keysPressed.delete(e.keyCode);
});
(function update() {
requestAnimationFrame(update);
keysPressed.forEach(k => {
if (k in keyCodesToActions) {
keyCodesToActions[k]();
}
});
ship.move();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 1.4);
// ^^^ optionally offset y a bit
// so the player can see better
ctx.rotate(-90 * Math.PI / 180 - ship.angle);
ctx.translate(-ship.x, -ship.y);
/* draw everything as normal */
const tileSize = ~~(canvas.width / 5);
for (let x = 0; x < map.width; x += tileSize) {
for (let y = 0; y < map.height; y += tileSize) {
// simple culling
if (x > ship.x + canvas.width || y > ship.y + canvas.height ||
x < ship.x - canvas.width || y < ship.y - canvas.height) {
continue;
}
const light = ((x / tileSize + y / tileSize) & 1) * 5 + 70;
ctx.fillStyle = `hsl(${360 - (x + y) / 10}, 50%, ${light}%)`;
ctx.fillRect(x, y, tileSize + 1, tileSize + 1);
}
}
ship.draw(ctx);
ctx.restore();
})();
body {
margin: 0;
font-family: monospace;
display: flex;
flex-flow: row nowrap;
align-items: center;
}
html, body {
height: 100%;
}
canvas {
background: #eee;
border: 4px solid #222;
}
div {
transform: rotate(-90deg);
background: #222;
color: #fff;
padding: 2px;
}
<div>arrow keys to move</div>
See this related answer for an example of the player-perspective viewport with a physics engine.
The way you're going about it right now seems correct to me. I would change the "20" bounds to a variable though, so you can easily change the bounds of a level or the entire game if you ever require so.
You could abstract this logic into a specific "Viewport" method, that would simply handle the calculations required to determine where your "Camera" needs to be on the map, and then make sure the X and Y coordinates of your character match the center of your camera.
You could also flip that method and determine the location of your camera based on the characters position (e.g.: (position.x - (desired_camera_size.width / 2))) and draw the camera from there on out.
When you have your camera position figured out, you can start worrying about drawing the room itself as the first layer of your canvas.
Save the code below as a .HTM (.html) file and open in your browser.
The result should match this screen shot EXACTLY.
Here is some example code that maps viewports of different sizes onto each other.
Though this implementation uses pixels, you could expand upon this logic to render
tiles. I actually store my tilemaps as .PNG files. Depending on the color of the
pixel, it can represent a different tile type. The code here is designed to sample
from viewports 1,2, or 3 and paste results into viewport 0.
Youtube Video Playlist For The Screenshot and Code Directly Below : REC_MAP
EDIT: REC_MAP.HTM CODE MOVED TO PASTEBIN:
https://pastebin.com/9hWs8Bag
Part #2: BUF_VEW.HTM (Sampling from off screen buffer)
We are going to refactor the code from the previous demo so that
our source viewport samples a bitmap that is off screen. Eventually
we will interpret each pixel color on the bitmap as a unique tile value.
We don't go that far in this code, this is just a refactor to get one
of our viewports off-screen. I recorded the entire process here.
No edits. Entire process including me taking way too long to think
up variable names.
Youtube Video Playlist For The Screenshot and Code Directly Below : BUF_VEW
As before, you can take this source code, save it as a .HTM (.html) file, and run it in your browser.
EDIT: BUF_VEW.HTM CODE MOVED TO PASTEBIN:
https://pastebin.com/zedhD60u
Part #3: UIN_ADA.HTM ( User Input Adapter & Snapping Camera )
We are now going to edit the previous BUF_VEW.HTM file from
part #2 and add 2 new pieces of functionality.
1: User input handling
2: A camera that can zoom in and out and be moved.
This camera will move in increments of it's own viewport
selection area width and height, meaning the motion will
be very "snappy". This camera is designed for level editing,
not really in-game play. We are focusing on a level editor
camera first. The long-term end goal is to make the editor-code
and the in-game-play code the same code. The only difference
should be that when in game-play mode the camera will behave
differently and tile-map editing will be disabled.
Youtube Video Playlist For The Screenshot And Code Directly Below: UIN_ADA
Copy code below, save as: "UIN_ADA.HTM" and run in browser.
Controls: Arrows & "+" "-" for camera zoom-in, zoom-out.
EDIT: UIN_ADA.HTM MOVED TO PASTEBIN:
https://pastebin.com/ntmWihra
Part #4: DAS_BOR.HTM ( DAShed_BOaRders )
We are going to do some calculations to draw a 1 pixel
thin boarder around each tile. The result won't be fancy,
but it will help us verify that we are able to get the
local coordinates of each tile and do something useful with
them. These tile-local coordinates will be necessary for
mapping a bitmap image onto the tile in later installments.
Youtube_Playlist: DAS_BOR.HTM
Source_Code: DAS_BOR.HTM
Part #5: Zoom + Pan over WebGL Canvas fragment shader code:
This is the math required for zooming and panning over a
shader written in GLSL. Rather than taking a sub-sample of off-screen
data, we take a sub-sample of the gl_FragCoord values. The math here
allows for an inset on-screen viewport and a camera that can
zoom and pan over your shader. If you have done a shader tutorial
by "Lewis Lepton" and you would like to zoom and pan over it,
you can filter his input coordinates through this logic and that
should do it.
JavaScript Code
Quick Video Explanation Of Code
Part #6: ICOG.JS : WebGL2 port of DAS_BOR.HTM
To run this you'll need to include the script in an otherwise
empty .HTM file. It replicates the same behavior found in DAS_BOR.HTM,
except all of the rendering is done with GLSL shader code.
There is also the makings of a full game framework in the code as well.
Usage:
1: Press "~" to tell the master editor to read input.
2: Press "2" to enter editor #2 which is the tile editor.
3: WASD to move over 512x512 memory sub sections.
4: Arrow Keys to move camera over by exactly 1 camera.
5: "+" and "-" keys to change the "zoom level" of the camera.
Though this code simply renders each tile value as a gradient square,
it demonstrates the ability to get the correct tile value and internal
coordinates of current tile being draw. Armed with the local coordinates
of a tile in your shader code, you have the ground-work math in place
for mapping images onto these tiles.
Full JavaScript Webgl2 Code
Youtube playlist documenting creation of ICOG.JS
//|StackOverflow Says:
//|Links to pastebin.com must be accompanied by code. Please |//
//|indent all code by 4 spaces using the code toolbar button |//
//|or the CTRL+K keyboard shortcut. For more editing help, |//
//|click the [?] toolbar icon. |//
//| |//
//|StackOverflow Also Says (when I include the code here) |//
//|You are over you 30,000 character limit for posts. |//
function(){ console.log("[FixingStackOverflowComplaint]"); }

Categories

Resources