drawImage() doesn't work properly - javascript

When I draw a line, it is drawn and appears fine, but when I draw a new line again, the last thing I drew disappears. It's like resetting after I draw a new line again.
Here's my code:
function draw() {
var teethImage = new Image();
teethImage.onload = function () {
};
teethImage.src = "images/teeth.png";
ctx.drawImage(teethImage, 1, 1);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
}
What's wrong in my code?

I already fixed the error. I just simply load the image on the init().
Because the reason why it is resetting, it displays again a new image, thus, it overwrites the image.

here try this:
draw();
function draw() {
var canvas = document.getElementById('myCanvas'),
ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
ctx.drawImage(img, 1, 1);
ctx.moveTo(0,0); // startX,startY (i mean 'start point which you want:x, start point which you want:y')
ctx.lineTo(img.width, img.height);
ctx.lineTo(img.width/3, img.height/2);
ctx.lineTo(img.width, 0);
ctx.strokeStyle = '#fff'; //you used (strokeStyle(x), what is x)
ctx.lineWidth = 7;
ctx.stroke();
};
img.src = "http://bermangraphics.com/images/jury-images-13.jpg";
}
You can examine strokeStyle
JsFiddle Demo

Related

How to execute a function after another one that has an onload function inside it?

I want to display an image(dinamically) on the canvas and then reset it.
drawImage() is the function that draws the image on the canvas after its source is loaded.
resetCanvas() is the function that resets/clean the canvas.
var canvas = document.getElementById("Canvas");
const ctx = canvas.getContext("2d");
drawImage("img/earth.jpg");
resetCanvas();
//more code
function resetCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function drawImage(source) {
var img = new Image();
img.onload = function() {
var x = img.width;
var y = img.height;
adjustCanvasSize(x, y);
ctx.drawImage(img,0,0, x, y);
}
img.src = source;
}
When I execute this code, the resetCanvas() is "ignored". I don't want to insert the resetCanvas() inside the onload function of the drawImage() as it actually represents many other distinct functions and instructions that are going to be executed after the drawImage() and it would look wrong.
I was thinking if there was a way of making javascript more patient and stop it from executing anything until the image gets loaded in the drawImage function.
A few comments:
If you reset the canvas after drawing the image you you won't see the image since the resetCanvas function is deleting everything you previously draw on the canvas
There are some problems when working with images in canvas. Please read this article: MDM Using images
Next come my code. I hope it helps.
var canvas = document.getElementById("Canvas");
const ctx = canvas.getContext("2d");
resetCanvas();
drawImage("https://cdn.sstatic.net/Sites/stackoverflow/img/404.svg");
//more code
function resetCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function drawImage(source) {
var img = new Image();
img.onload = function() {
var x = img.width;
var y = img.height;
adjustCanvasSize(canvas,x, y);
ctx.drawImage(img,0,0, x, y);
}
img.src = source;
}
function adjustCanvasSize(canvas, x, y){
canvas.width = x;
canvas.height = y;
}
canvas{border:1px solid;}
<canvas id="Canvas"></canvas>

Image isn't drawn after canvas is cleared (html5 canvas)

I am trying to make a variant of the boomshine game in javascript and everything works when I draw a circular shape with the arc function. However when i try to replace the arc function with the drawImage function to use a coin image instead of a circular shape I start having problems when I clear the canvas to delete the previous drawn circular shapes. If I don't clear the canvas before rendering the images, the images are drawn on the canvas except the old images are still on the canvas. But when i do clear the canvas before rendering the images again, nothing is drawn on the canvas.
I have included screenshots, the links are below.
This is how I clear the canvas:
var ctx = game.context;
ctx.fillStyle = "darkgray";
ctx.fillRect(0, 0, game.canvas.width, game.canvas.height);
This is how i draw the image:
function drawImageBall(x,y,radius,startAngle,color)
{
var img = document.createElement('img');
img.src = 'img/coin-icon.png';
var tmpCtx= game.context;
var ax = x-radius;
var ay = y-radius;
img.onload = function() {
tmpCtx.save();
tmpCtx.beginPath();
tmpCtx.arc(x, y, radius, 0, Math.PI * 2, true);
tmpCtx.closePath();
tmpCtx.clip();
tmpCtx.drawImage(img, ax, ay, img.width, img.height);
tmpCtx.beginPath();
tmpCtx.arc(0, 0, radius, 0, Math.PI * 2, true);
tmpCtx.clip();
tmpCtx.closePath();
tmpCtx.restore();
};
}
Clearing canvas (screenshot)
Without clearing canvas (screenshot)
Keep in mind that downloading the img will take some time.
During that downloading time, Javascript does not stop(!). Instead JS will continue executing any following code. This is causing your unexpected problems.
So download the img just once at the start of your app. That way your drawImage will be done in the order that you expect because there will be no delay while your image is downloading.
Using your code, I maked some changes, I removed the tmpTcx.clip(), look the fidlle. Tip: For performace questions you don't need load the image every time that you want write the canvas.
Poor Example: https://jsfiddle.net/wf4z0d2h/1/
function clearCanvas(){
var ctx = game.context;
ctx.fillStyle = "darkgray";
ctx.fillRect(0, 0, game.canvas.width, game.canvas.height);
}
function drawImageBall(x,y,radius,startAngle,color)
{
if(x == undefined){x = 100;}
if(y == undefined){y = 100;}
if(radius == undefined){radius = 40;}
//var img = document.createElement('img');
//img.src = 'img/coin-icon.png';
//img.src = "http://ps2.lansa.com/images/icons/normal/256/coin_256.png";
var tmpCtx= game.context;
var ax = x-radius;
var ay = y-radius;
//img.onload = function() {
tmpCtx.save();
tmpCtx.beginPath();
tmpCtx.arc(x, y, radius, 0, Math.PI * 2, true);
tmpCtx.stroke(); // Draw it
tmpCtx.closePath();
//tmpCtx.clip();
tmpCtx.drawImage(img, ax, ay, img.width, img.height);
//tmpCtx.beginPath();
//tmpCtx.arc(0, 0, radius, 0, Math.PI * 2, true);
////tmpCtx.clip();
//tmpCtx.stroke(); // Draw it
//tmpCtx.closePath();
//tmpCtx.restore();
//};
}
var img = document.createElement('img');
//img.src = 'img/coin-icon.png';
img.src = "http://ps2.lansa.com/images/icons/normal/256/coin_256.png";
//drawImageBall();
img.onload = function(){
x = 0;
y = 0;
setInterval(function(){
x = x+10;
y = y+10;
clearCanvas();
drawImageBall(x,y);
},300);
}

Clip canvas strokes to image

I'm trying to animate a pen filling in a variable width shape, currently working with html5 canvas. Ideally, I want to be able to have the sample below both start light and get colored in dark, as well as not appear at all and get colored in as though being drawn from nothing.
source-in doesn't seem to work, at least in firefox.
The image in question is a simple-ish SVG path, so if there's a reasonable way to generate canvas clip paths from SVG bezier paths, that would work as well.
var img = new Image();
img.src = "data:image/svg+xml;base64,...";
var xRecords = [...];
var yRecords = [...];
var canvas = document.getElementById("topCanvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
ctx.strokeStyle = "#0000ff";
ctx.lineWidth = 90;
ctx.beginPath();
ctx.lineCap = "round";
ctx.moveTo(xRecords[0], yRecords[0]);
for(var i = 0; i < xRecords.length; i++) {
ctx.lineTo(xRecords[i], yRecords[i]);
ctx.stroke();
}
http://codepen.io/matelich/pen/gpLmOW
Generating alternate versions of the image is not a big deal if that would help. Oh and the animation is just a sample.
Update This works for the most part on Chrome and IE, but not on Firefox: http://codepen.io/matelich/pen/pJNeRq
FF doesn't like your SVG dataURL.
Option#1:
You could use a .png image instead.
Option#2:
You can create a cubic Bezier curve (like SVG's "C") in canvas using context.moveTo and context.bezierCurveTo.
Then your compositing will work fine even in FF:
var canvas = document.getElementById("topCanvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload=start;
img.src = 'https://dl.dropboxusercontent.com/u/139992952/multple/svg2png.png';
var xRecords = [117.6970666666671, 137.5037866666671, 139.6247579166671, 138.2627966666671, 134.75555041666712, 130.4406666666671, 126.65579291666711, 124.7385766666671, 126.0266654166671, 131.8577066666671, 155.5330366666671, 191.76562666666712, 224.94953666666714, 239.47882666666712];
var yRecords = [143.95648000000128, 200.21077333333463, 232.21213000000128, 264.735546666668, 296.24260333333467, 325.19488000000126, 350.05395666666794, 369.2814133333347, 381.33883000000134, 384.687786666668, 371.9640133333346, 346.7872000000013, 322.15182666666794, 311.05237333333463];
function start(){
canvas.width=img.width;
canvas.height=img.height;
ctx.beginPath();
ctx.rect(0, 0, 640, 640);
ctx.fillStyle = 'white';
ctx.fill();
ctx.globalCompositeOperation = "darker";
ctx.drawImage(img, 0, 0);
ctx.globalCompositeOperation = "lighter";
ctx.drawImage(img, 0, 0);
ctx.globalCompositeOperation = "xor";
ctx.drawImage(img, 0, 0);
ctx.globalCompositeOperation = "destination-over";
ctx.strokeStyle = "#0000ff";
ctx.lineWidth = 90;
ctx.beginPath();
ctx.lineCap = "round";
ctx.moveTo(xRecords[0], yRecords[0]);
var i = 0;
function drawNext()
{
i++;
console.log(i+"!");
if(i >= xRecords.length) { return; }
ctx.lineTo(xRecords[i], yRecords[i]);
ctx.stroke();
setTimeout(drawNext, 500);
}
drawNext();
}
body{ background-color: white; }
#canvas{border:1px solid red;}
<canvas id="topCanvas" width=300 height=300></canvas>

Canvas - clipping multiple images

I want to clip a bunch of images into hexagon shapes.
I have it sort of working, but the clipping is across all the hexes instead of each image clipping to only one hex. What am I doing wrong?
Here's a live demo:
http://codepen.io/tev/pen/iJaHB
Here's the js in question:
function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise, img, imgX, imgY) {
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.moveTo(radius,0);
for (var i = 1; i < sides; i++) {
ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
}
ctx.closePath();
// add stroke
ctx.lineWidth = 5;
ctx.strokeStyle = '#056e96';
ctx.stroke();
// add stroke
ctx.lineWidth = 4;
ctx.strokeStyle = '#47b6c8';
ctx.stroke();
// add stroke
ctx.lineWidth = 2;
ctx.strokeStyle = '#056e96';
ctx.stroke();
// Clip to the current path
ctx.clip();
ctx.drawImage(img, imgX, imgY);
ctx.restore();
}
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
// Create an image element
var img = document.createElement('IMG');
var img2 = document.createElement('IMG');
// When the image is loaded, draw it
img.onload = function () {
polygon(ctx, 120,120,100,6, 0,0,img, -120,-170);
}
img2.onload = function () {
polygon(ctx, 280,212,100,6, 0,0,img2, -150,-120);
}
// Specify the src to load the image
img.src = "http://farm8.staticflickr.com/7381/9601443923_051d985646_n.jpg";
img2.src = "http://farm6.staticflickr.com/5496/9585303170_d005d2aaa9_n.jpg";
You need to add this to your polygon() method:
ctx.beginPath();
See modified pen here
function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise, img, ...
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.beginPath(); /// for example here, before moveTo/lineTo
ctx.moveTo(radius,0);
...
If not the lines will accumulate so the second time you call polygon the previous polygon will still exist. That's why you see the image partly inside the first hexagon as well.

How to redraw canvas (every 250ms) without flickering between each redraw?

I wrote a function that draws out a slice of a pizza based on how big you specify it to be (in degrees)
function drawProgress(degs){
var canvas = document.getElementById('progress');
var context = canvas.getContext('2d');
context.globalAlpha=1;
var img = new Image();
img.onload = function(){
context.beginPath();
context.arc(canvas.width/2,canvas.height/2, canvas.height/2, 0, degs * (-Math.PI/180), true);
context.lineTo(canvas.width/2, canvas.height/2);
context.clip();
context.drawImage(img, 0, 0, canvas.width,canvas.width);
}
img.src = 'pizza.png';
}
When I try to call this function every 250ms, the progress is not updated after the first draw.
function runsEvery250ms(percent){
drawProgress(3.6 * percent);
}
What changes do I need to make to the code to get the canvas to redraw each time drawProgress(degs) is called? Is it possible to perform redraws without causing the pizza to flicker?
Use context.clearRect(0, 0, canvas.width, canvas.height); and cache your image, don't reload each time you refresh
UPDATE: No idea if this will work, untested and been a while since I used canvas but try it
var canvas = document.getElementById('progress');
var context = canvas.getContext('2d');
var img = new Image();
var imgLoaded = false;
img.src = 'pizza.png';
img.onload = function(){
imgLoaded = true;
}
function drawProgress(degs){
context.save();
context.clearRect(0, 0, canvas.width, canvas.height);
context.globalAlpha=1;
context.beginPath();
context.arc(canvas.width/2,canvas.height/2, canvas.height/2, 0, degs * (-Math.PI/180), true);
context.lineTo(canvas.width/2, canvas.height/2);
context.clip();
if (imgLoaded) context.drawImage(img, 0, 0, canvas.width,canvas.width);
context.restore();
}

Categories

Resources