Updating canvas animation width on window resize - javascript

Can't figure out how to get this in place. I have the right function firing but am lost when it comes to why the logic isn't working my script. I have a console.log to show the variables are updating but the animation width doesn't update with it.
Javascript
$( document ).ready(function() {
var imgTag = new Image();
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x = canvas.width;
var y = 0;
imgTag.onload = animate;
imgTag.src = "http://foodhall.hellogriptest.com/hh/assets/medallion-bounce.png";
var h = window.innerHeight;
var w = window.innerWidth;
canvas.height = h;
canvas.width = w;
//moving image
var mover = {
x: 0,
y: 0,
width: 100,
height: 100,
color: '#000',
down: true,
right: true
}
function animate() {
clear();
render();
rID = requestAnimationFrame(animate);
}
function clear() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
function render() {
//set direction
if (mover.down && mover.y >= h - mover.height)
mover.down = false;
if (!mover.down && mover.y <= 0)
mover.down = true;
if (mover.right && mover.x >= w - mover.width)
mover.right = false;
if (!mover.right && mover.x <= 0)
mover.right = true;
//make move
if (mover.right)
mover.x += 6;
else
mover.x -= 6;
if (mover.down)
mover.y += 6;
else
mover.y -= 6;
//drawRectangle(mover);
drawImage(mover);
}
function drawImage(mover) {
context.drawImage(imgTag, mover.x, mover.y); // draw image at current position
}
window.onresize = function() {
W = window.innerWidth;
H = window.innerHeight;
canvas.width = W;
canvas.height = H;
x = W;
console.log(x);
clear();
render();
drawImage(mover);
}
});//ready
Codepen
—
https://codepen.io/alcoven/pen/KROPrK

This is a simple fix. In the beginning of your script, you are setting lowercase w and lowercase h to the width and height of the window, but in you resize function, you set W = window.innerWidth. The capital W variable is then created and assigned the innerWidth. The lowercase w variable still exists as the original width, and that is what your render is using.

Related

How to check if a puzzle is solved using js?

I want know how to figure out if the puzzle is solved.
I am creating an app for creating custom 6-piece puzzle.
Here's the code:
function approved(){
// Get the canvas and context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Load the image
var img = new Image();
img.src = document.getElementById('puzzleprieview').src;
img.onload = function() {
// Set the canvas size
canvas.width = img.width;
canvas.height = img.height;
// Draw the image on the canvas
ctx.drawImage(img, 0, 0);
// Split the image into parts
var w = img.width / 3;
var h = img.height / 2;
for (var i = 0; i < 7; i++) {
var x = (i % 3) * w;
var y = Math.floor(i / 3) * h;
// Create a new canvas for each part
var partCanvas = document.createElement("canvas");
partCanvas.draggable="true";
partCanvas.className="sampcanvas"
$(".sampcanvas").draggable({snap: true});
partCanvas.width = w;
partCanvas.height = h;
var partCtx = partCanvas.getContext("2d");
// Draw the part of the image on the new canvas
partCtx.drawImage(canvas, x, y, w, h, 0, 0, w, h);
var number=Math.floor(Math.random() * 100);
// Do something with each part, such as append it to the document
const getRandom = (min, max) => Math.floor(Math.random()*(max-min+1)+min);
partCanvas.style.left= getRandom(0, 300 - 200)+'px'; // 👈🏼 Horizontally
partCanvas.style.top = getRandom(0, 300 - 200)+'px'; // 👈🏼 Vertically
document.getElementById('pieces').appendChild(partCanvas);
}
}
}
That code is used to create puzzle pieces and append them.
What I need to do is somehow compare the puzzle piece solving to the canvas that is created
Well, great task in general and question in particular !
To achieve this purpose you could, f.e. put into each puzzlePart block it's initial position using "data-" attributes:
var x = (i % 3) * w;
var y = Math.floor(i / 3) * h;
// Create a new canvas for each part
let partCanvas = document.createElement('canvas');
partCanvas.dataset.xx = x;
partCanvas.dataset.yy = y;
Next, whenever needed, you are able to compare current position of puzzle parts with their initial ones. I took initial position from .dataset and current using .getBoundingClientRect():
var canvasOffsets = canvas.getBoundingClientRect();
var elementScreenOffsets = partCanvas.getBoundingClientRect();
var elementOffsets = {
x: elementScreenOffsets.left - canvasOffsets.left,
y: elementScreenOffsets.top - canvasOffsets.top,
};
var initialOffsets = {
x: partCanvas.dataset.xx,
y: partCanvas.dataset.yy,
};
As an option, you could for example "freeze" puzzle parts on the screen when they're moreless in their initial position:
var FREEZE_DISTASNCE = 30;
if (
Math.abs(elementOffsets.x - initialOffsets.x) <
FREEZE_DISTASNCE &&
Math.abs(elementOffsets.y - initialOffsets.y) <
FREEZE_DISTASNCE
) {
makeNotDraggable(partCanvas);
partCanvas.style.left = partCanvas.dataset.xx;
partCanvas.style.top = partCanvas.dataset.yy;
partCanvas.style.zIndex = -1;
}
So eventually I decided to modify initial question's code to make it fully working using my ideas above. Plus I decided to implement this POC with "generic" image which you could pick
For drag-n-drop implementation I referenced this article: https://www.w3schools.com/howto/howto_js_draggable.asp
File inputs Api: https://developer.mozilla.org/ru/docs/Web/HTML/Element/Input/file
document
.querySelector('.js-puzzle-image')
.addEventListener('change', function () {
document.querySelector('.js-puzzle-image').style.display = 'none';
document.querySelector('#pieces').style.display = 'inline-block';
var imageSrc = window.URL.createObjectURL(this.files[0]);
approved(imageSrc);
});
function approved(imageSrc) {
const el_wrap = document.querySelector('#pieces');
// Get the canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// Load the image
var img = new Image();
img.src = imageSrc;
img.onload = function () {
// Set the canvas size
canvas.width = img.width;
canvas.height = img.height;
el_wrap.style.width = `${img.width}px`;
el_wrap.style.height = `${img.height}px`;
// Draw the image on the canvas
ctx.drawImage(img, 0, 0);
// Split the image into parts
var w = img.width / 3;
var h = img.height / 2;
for (var i = 0; i < 6; i++) {
var x = (i % 3) * w;
var y = Math.floor(i / 3) * h;
// Create a new canvas for each part
let partCanvas = document.createElement('canvas');
partCanvas.dataset.xx = x;
partCanvas.dataset.yy = y;
partCanvas.draggable = 'true';
partCanvas.className = 'sampcanvas';
//$('.sampcanvas').draggable({ snap: true });
partCanvas.width = w;
partCanvas.height = h;
var partCtx = partCanvas.getContext('2d');
// Draw the part of the image on the new canvas
partCtx.drawImage(canvas, x, y, w, h, 0, 0, w, h);
// Do something with each part, such as append it to the document
const getRandom = (min, max) =>
Math.floor(Math.random() * (max - min + 1) + min);
partCanvas.style.left = getRandom(0, img.width - w) + 'px'; // 👈🏼 Horizontally
partCanvas.style.top = getRandom(0, img.height - h) + 'px'; // 👈🏼 Vertically
document.getElementById('pieces').appendChild(partCanvas);
// making elements "draggable", but "freeze" them when they're on the correct position
makeDraggable(partCanvas, () => {
var canvasOffsets = canvas.getBoundingClientRect();
var elementScreenOffsets = partCanvas.getBoundingClientRect();
var elementOffsets = {
x: elementScreenOffsets.left - canvasOffsets.left,
y: elementScreenOffsets.top - canvasOffsets.top,
};
var initialOffsets = {
x: partCanvas.dataset.xx,
y: partCanvas.dataset.yy,
};
var FREEZE_DISTASNCE = 30;
if (
Math.abs(elementOffsets.x - initialOffsets.x) <
FREEZE_DISTASNCE &&
Math.abs(elementOffsets.y - initialOffsets.y) <
FREEZE_DISTASNCE
) {
makeNotDraggable(partCanvas);
partCanvas.style.left = partCanvas.dataset.xx + 'px';
partCanvas.style.top = partCanvas.dataset.yy + 'px';
partCanvas.style.zIndex = -1;
}
});
}
canvas.style.display = 'none';
};
}
// https://www.w3schools.com/howto/howto_js_draggable.asp
var zIndexTracker = 0;
function makeNotDraggable(elmnt) {
elmnt.onmousedown = undefined;
}
function makeDraggable(elmnt, onDrop) {
var pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
elmnt.onmousedown = dragMouseDown;
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
elmnt.style.zIndex = ++zIndexTracker;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = elmnt.offsetTop - pos2 + 'px';
elmnt.style.left = elmnt.offsetLeft - pos1 + 'px';
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
onDrop();
}
}
#pieces {
position: relative;
border: 1px dashed red;
display: inline-block;
}
.sampcanvas {
position: absolute;
}
<input type="file" accept=".png, .jpg, .jpeg" class="js-puzzle-image" />
<div id="pieces" style="display: none">
<canvas id="canvas"></canvas>
</div>
Of course, this code snippet is "not ideal" from code quality perspective and should be re-worked to be more object-oriented, to have better code responsibility splitting, etc... But for demostration purposes, I believe, that's a good start
Try adding this
partCanvas.dataset.index = i;
and then you can in your drop function do something like this
const finished = () => {
const indexes = document.querySelectorAll('.sampcanvas')
.map(imgPart => imgPart.dataset.index)
.join('');
console.log(indexes);
return indexes === '0123456';
}

Double image background on canvas not sharing the same size

I'm trying to make a section on a website have two background images that will reveal the bottom one as the pointer moves across the screen.
I'm still new to javascript, and my code is made up of bits and pieces that I've found on google, but I can't seem to get the top image to share the same resolution and image size for whatever reason as the bottom image.
Here is the link to my codepen: https://codepen.io/Awktopus/pen/zYwKOKO
And here is my code:
HTML:
<canvas id="main-canvas" id="canvas-size" class="background-size"></canvas>
<image src="https://i.imgur.com/PbGAAIy.jpg" id="upper-image" class="hidden-bg"></img>
<image src="https://i.imgur.com/Gx14sKW.jpg" id="lower-image" class="hidden-bg"></img>
CSS:
.hidden-bg {
display: none;
}
JS:
var can = document.getElementById('main-canvas');
var ctx = can.getContext('2d');
can.width = window.innerWidth;
can.height = window.innerWidth / 2;
var upperImg = document.getElementById("upper-image");
var lowerImg = document.getElementById("lower-image");
var pat = ctx.createPattern(upperImg, "no-repeat");
var canvas = ctx.canvas ;
var hRatio = canvas.width / lowerImg.width ;
var vRatio = canvas.height / lowerImg.height ;
var ratio = Math.max ( hRatio, vRatio );
var centerShift_x = ( canvas.width - lowerImg.width*ratio ) / 2;
var centerShift_y = ( canvas.height - lowerImg.height*ratio ) / 2;
can.addEventListener('mousemove', function(e) {
var mouse = getMouse(e, can);
redraw(mouse);
}, false);
function redraw(mouse) {
can.width = can.width;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(lowerImg, 0,0, lowerImg.width, lowerImg.height, centerShift_x,centerShift_y,lowerImg.width*ratio, lowerImg.height*ratio);
ctx.beginPath();
ctx.rect(0,0,can.width,can.height);
ctx.arc(mouse.x, mouse.y, 250, 0, Math.PI*2, true)
ctx.clip();
ctx.fillStyle = pat;
ctx.fillRect(0, 0, lowerImg.width, lowerImg.height, centerShift_x, centerShift_y, lowerImg.width*ratio, lowerImg.height*ratio);
}
var img = new Image();
img.onload = function() {
redraw({x: -500, y:-500})
}
function getMouse(e, canvas) {
var element = canvas,
offsetX = 0,
offsetY = 0,
mx, my;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
return {
x: mx,
y: my
};
}
If I understood this right you will want to set the width and height and draw the upper image using drawImage(). Just use the same ratios as the lowerImage. No need to use createPattern for this.
codepen: https://codepen.io/jfirestorm44/pen/BaRLoxX
var can = document.getElementById('main-canvas');
var ctx = can.getContext('2d');
can.width = window.innerWidth;
can.height = window.innerWidth / 2;
var upperImg = document.getElementById("upper-image");
var lowerImg = document.getElementById("lower-image");
//var pat = ctx.createPattern(upperImg, "no-repeat");
var canvas = ctx.canvas ;
var hRatio = canvas.width / lowerImg.width ;
var vRatio = canvas.height / lowerImg.height ;
var ratio = Math.max ( hRatio, vRatio );
var centerShift_x = ( canvas.width - lowerImg.width*ratio ) / 2;
var centerShift_y = ( canvas.height - lowerImg.height*ratio ) / 2;
can.addEventListener('mousemove', function(e) {
var mouse = getMouse(e, can);
redraw(mouse);
}, false);
function redraw(mouse) {
can.width = can.width;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(lowerImg, 0,0, lowerImg.width, lowerImg.height, centerShift_x,centerShift_y,lowerImg.width*ratio, lowerImg.height*ratio);
ctx.beginPath();
ctx.rect(0,0,can.width,can.height);
ctx.arc(mouse.x, mouse.y, 250, 0, Math.PI*2, true)
ctx.clip();
ctx.drawImage(upperImg, 0,0, lowerImg.width, lowerImg.height, centerShift_x,centerShift_y,lowerImg.width*ratio, lowerImg.height*ratio);
}
var img = new Image();
img.onload = function() {
redraw({x: -500, y:-500})
}
function getMouse(e, canvas) {
var element = canvas,
offsetX = 0,
offsetY = 0,
mx, my;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
return {
x: mx,
y: my
};
}
.hidden-bg {
display: none;
}
<canvas id="main-canvas" id="canvas-size" class="background-size"></canvas>
<image src="https://i.imgur.com/PbGAAIy.jpg" id="upper-image" class="hidden-bg"></img>
<image src="https://i.imgur.com/Gx14sKW.jpg" id="lower-image" class="hidden-bg"></img>

HTML Canvas, blurring drawn polygon

I made this (run snippet below)
var Canvas = document.getElementById('c');
var ctx = Canvas.getContext('2d');
var resize = function() {
Canvas.width = Canvas.clientWidth;
Canvas.height = Canvas.clientHeight;
};
window.addEventListener('resize', resize);
resize();
var elements = [];
var presets = {};
presets.shard = function (x, y, s, random, color) {
return {
x: x,
y: y,
draw: function(ctx, t) {
this.x += 0;
this.y += 0;
var posX = this.x + + Math.sin((50 + x + (t / 10)) / 100) * 5;
var posy = this.y + + Math.sin((55 + x + (t / 10)) / 100) * 7;
ctx.beginPath();
ctx.fillStyle = color;
ctx.moveTo(posX, posy);
ctx.lineTo(posX+random,posy+random);
ctx.lineTo(posX+random,posy+random);
ctx.lineTo(posX+0,posy+50);
ctx.closePath();
ctx.fill();
}
}
};
for(var x = 0; x < Canvas.width; x++) {
for(var y = 0; y < Canvas.height; y++) {
if(Math.round(Math.random() * 60000) == 1) {
var s = ((Math.random() * 5) + 1) / 10;
if(Math.round(Math.random()) == 1){
var random = Math.floor(Math.random() * 100) + 10;
var colorRanges = ['#8c8886', '#9c9995'];
var color = colorRanges[Math.floor(Math.random() * colorRanges.length)];
elements.push(presets.shard(x, y, s, random, color));
}
}
}
}
setInterval(function() {
ctx.clearRect(0, 0, Canvas.width, Canvas.height);
var time = new Date().getTime();
for (var e in elements)
elements[e].draw(ctx, time);
}, 10);
<canvas id="c" width="1000" height="1000"\>
I just need to add one feature to be able to use it on the site I'm building it for. Some of the floating shards need to be blurred to give a sense of depth.
Can Canvas do this, and if so, how?
context.filter = 'blur(10px)';
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter
I used this few months ago, maybe it could work for you as well :
var canvas = document.getElementById("heroCanvas");
var canvasContext = canvas.getContext("2d");
var canvasBackground = new Image();
canvasBackground.src = "image.jpg";
var drawBlur = function() {
// Store the width and height of the canvas for below
var w = canvas.width;
var h = canvas.height;
// This draws the image we just loaded to our canvas
canvasContext.drawImage(canvasBackground, 0, 0, w, h);
// This blurs the contents of the entire canvas
stackBlurCanvasRGBA("heroCanvas", 0, 0, w, h, 100);
}
canvasBackground.onload = function() {
drawBlur();
}
Here the source : http://zurb.com/playground/image-blur-texture

Add annotation to image with canvas on small screen without resizing

I hope you can help me with my problem. I am writing a mobile application with cordova and ionic and we need a function to annotate images before we upload them.
I want to be able to add annotations to an image (at the moment only lines) without resizing the image. But since the screenspace on phones is small i am now using 2 canvas directly placed above each other.
One the first one i render the scaled down image i want to annotate, on the 2nd one i make the annotations. Then i render the original image on 3 canvas and upscale the annotations to the size of the original image.
var finalcanvas = document.createElement('canvas');
var ctxfinal = finalcanvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function() {
finalcanvas.width = imageObj.width;
finalcanvas.height = imageObj.height;
ctxfinal.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height);
var canvaslines = document.getElementById("canvasdraw");
ctxfinal.drawImage(canvaslines, 0, 0, imageObj.width, imageObj.height);
$scope.editimage.image = finalcanvas.toDataURL("image/jpeg");
This works fine, but the only downside is that the annotations are rather pixely. I assume there must be a library or something which should make things like this easier, but no matter how much i searched i could not find anything. But maybe i used the wrong keywords since i am not a very adept programmer and not a native speaker. Thanks for all your help in advance
Edit: Here is a link to a jsfiddle of my code http://jsfiddle.net/q97szydq/14/
One solution would be to store all your points into an array, then redraw them on your new canvas (after you rescaled the points) :
var drawnLines = [];
//in your start functions :
drawnLines.push(["m", x, y]);
//in your move functions :
drawnLines.push(["l", x, y]);
//then in your hideModal function :
var ratio = finalcanvas.width/document.getElementById("canvasdraw").width;
ctxfinal.lineWidth = 3*ratio;
for(i=0; i<drawnLines.length; i++){
var xm = drawnLines[i][1]*ratio;
var ym = drawnLines[i][2]*ratio;
switch (drawnLines[i][0]){
case "l" : ctxfinal.lineTo(xm, ym);
case "m" : ctxfinal.moveTo(xm, ym);
}
}
ctxfinal.stroke();
ctx = document.getElementById("canvasdraw").getContext("2d");
ctx2 = document.getElementById("canvasimg").getContext("2d");
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 3;
var imageObj = new Image();
imageObj.onload = function() { //ion-header-bar
var MAX_WIDTH = 300;
var MAX_HEIGHT = 500;
tempW = imageObj.width;
tempH = imageObj.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
document.getElementById("canvasdraw").height = tempH;
document.getElementById("canvasdraw").width = tempW;
document.getElementById("canvasimg").height = tempH;
document.getElementById("canvasimg").width = tempW;
ctx2.drawImage(imageObj, 0, 0, tempW, tempH);
};
imageObj.src = "http://images2.fanpop.com/image/photos/12900000/Cute-kittens-12929201-1600-1200.jpg";
// setup to trigger drawing on mouse or touch
drawTouch();
drawPointer();
drawMouse();
var drawnLines = [];
//all draw functions have minus 50px height to adjust for header
// prototype to start drawing on touch using canvas moveTo and lineTo
function drawTouch() {
var start = function(e) {
ctx.beginPath();
x = e.changedTouches[0].pageX;
y = e.changedTouches[0].pageY - 50;
ctx.moveTo(x, y);
drawnLines.push(["m", x, y]);
};
var move = function(e) {
e.preventDefault();
x = e.changedTouches[0].pageX;
y = e.changedTouches[0].pageY - 50;
ctx.lineTo(x, y);
ctx.stroke();
drawnLines.push(["l", x, y]);
};
document.getElementById("canvasdraw").addEventListener("touchstart", start, false);
document.getElementById("canvasdraw").addEventListener("touchmove", move, false);
};
// prototype to start drawing on pointer(microsoft ie) using canvas moveTo and lineTo
function drawPointer() {
var start = function(e) {
e = e.originalEvent;
ctx.beginPath();
x = e.pageX;
y = e.pageY - 50;
ctx.moveTo(x, y);
drawnLines.push(["m", x, y]);
};
var move = function(e) {
e.preventDefault();
e = e.originalEvent;
x = e.pageX;
y = e.pageY - 50;
ctx.lineTo(x, y);
ctx.stroke();
drawnLines.push(["l", x, y]);
};
document.getElementById("canvasdraw").addEventListener("MSPointerDown", start, false);
document.getElementById("canvasdraw").addEventListener("MSPointerMove", move, false);
};
// prototype to start drawing on mouse using canvas moveTo and lineTo
function drawMouse() {
var clicked = 0;
var start = function(e) {
clicked = 1;
ctx.beginPath();
x = e.pageX;
y = e.pageY - 50;
ctx.moveTo(x, y);
drawnLines.push(["m", x, y]);
};
var move = function(e) {
if (clicked) {
x = e.pageX;
y = e.pageY - 50;
ctx.lineTo(x, y);
ctx.stroke();
drawnLines.push(["l", x, y]);
}
};
var stop = function(e) {
clicked = 0;
};
document.getElementById("canvasdraw").addEventListener("mousedown", start, false);
document.getElementById("canvasdraw").addEventListener("mousemove", move, false);
document.addEventListener("mouseup", stop, false);
};
var hideModal = function() {
var finalcanvas = document.getElementById("finalcanvas");
var ctxfinal = finalcanvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function() {
finalcanvas.width = imageObj.width;
finalcanvas.height = imageObj.height;
ctxfinal.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height);
ctxfinal.beginPath();
var ratio = finalcanvas.width / document.getElementById("canvasdraw").width;
ctxfinal.lineWidth = 3 * ratio;
for (i = 0; i < drawnLines.length; i++) {
var xm = drawnLines[i][1] * ratio;
var ym = drawnLines[i][2] * ratio;
switch (drawnLines[i][0]) {
case "l":
ctxfinal.lineTo(xm, ym);
case "m":
ctxfinal.moveTo(xm, ym);
}
}
ctxfinal.stroke();
//I then generate a a image from this final canvas. So now i have the image in the original size + the sadly a bit pixely annotations
//$scope.editimage.image = finalcanvas.toDataURL("image/jpeg");
};
imageObj.src = "http://images2.fanpop.com/image/photos/12900000/Cute-kittens-12929201-1600-1200.jpg";
};
canvas {
border: 1px solid #000;
}
<div id="page">
<div class="buttons" style="height:50px;">
<button class="button button-clear" onclick="hideModal()">save</button>
</div>
<canvas id="canvasimg" style="position:absolute;z-index:1;"></canvas>
<canvas id="canvasdraw" style="position:absolute;background:transparent;z-index:99;"></canvas>
</div>
<div style="position:absolute;top:300px;">
<canvas id="finalcanvas"></canvas>

Why isn't JavaScript resizing this image?

I am trying to do a simple animation example in JavaScript. However, I have an image and I have tried everything that I have found on the internet and seen on previous posts and all that but I can't figure out why this image won't resize. Can someone tell me what the problem is?
var x = 50;
var y = 20;
var xDirection = 1;
var yDirection = 1;
var image = new Image();
image.src = "http://2.bp.blogspot.com/-iS6eK4lSfi4/UJJRqbKA-VI/AAAAAAAABLA/HLxLJpCpau4/s320/Smiley-Face-2.jpg";
image.style.width = "50px";
image.style.height = "50px";
var canvas = null;
var context = null;
window.onload = init;
function init() {
canvas = document.getElementById("gameSurface");
context =canvas.getContext("2d");
setInterval(draw, 1000/30);
}
function draw() {
context.clearRect(0,0,500,500);
context.drawImage(image, x, y);
x += xDirection;
y += yDirection;
if ((x + 50) >= 500) {
x = 450;
xDirection = -1;
}else if (x <= 0) {
x = 0;
xDirection = 1;
}
if ((y + 50) >= 500) {
y = 450;
yDirection = -1;
}else if (y <= 0) {
y = 0;
yDirection = 1;
}
}
As you can see all I want is a smiley face bouncing around the screen. I seem to always have issues with JS... and I do not know anything about JQuery, sorry.
You're resizing the img element by setting its style, but the canvas .drawImage() method doesn't use the element style. However .drawImage() does let you specify the size if you provide additional arguments:
context.drawImage(image, x, y, 50, 50);
Demo: http://jsfiddle.net/vz28W/
See MDN for more details.

Categories