Why doesn't context.drawImage() work in html canvas? - javascript

I'm trying to put the image file "sticky.png" into a canvas box, but all I'm getting is a blank canvas. Can anyone point out what I'm doing wrong and/or give me code that works?
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
<body>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
sticky.src = "sticky.png";
};
</script>
</body>

You need to include the sticky.src before sticky.onload.
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.src = "sticky.png";
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
};
</script>
</body>
Fiddle

sometimes as a workAround we have to load the image before the canvas. It's very unusual, but it WORKS. And then you just hide the image. Don't forget to use setTimeOut to wait till image is loaded!
setTimeout("paintStar()", 2000);
function paintStar() {
var canva3 = document.getElementById('canvas3');
canva3.width = 640;
canva3.height = 480;
var ct3 = canva3.getContext('2d');
var img = new Image();
img.src = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo';
ct3.drawImage(img, 0, 0);
ct3.drawImage(img, 0, 0, 20, 20, 10, 200, 20, 20);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CANVAS</title>
<style>
.canvas-1 {
width: 640px;
height: 480px;
border: 1px solid #777;
}
.img-1 {
display: none;
}
</style>
<script src="canva3.js" defer></script>
</head>
<body>
<div class="img-1"><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo" alt=""></div>
<canvas id="canvas3" style="border: 2px solid #444;">Doesn't work!</canvas>
</body>
</html>

Related

Unexpected canvas behavior when using stroke style

I'm trying to clear one line by drawing another one on top of it on HTML canvas. But the second line becomes semi transparent for some unknown to me reason.
index.html
<!DOCTYPE html>
<head>
<script src="scripts.js" type="text/javascript"></script>
</head>
<html>
<body onload = "onload()">
<canvas id = "canvas" style="border: solid 1px; width: 200px; height: 200px;"></canvas>
</body>
</html>
scripts.js
var canvas,ctx;
const onload = () =>{
canvas = document.querySelector("#canvas")
ctx = canvas.getContext('2d')
drawLine("#ff0000")
drawLine("#ffffff")
}
const drawLine = (color) =>{
ctx.beginPath()
ctx.strokeStyle = color
ctx.moveTo(0,0)
ctx.lineTo(200,200)
ctx.stroke()
ctx.closePath()
}
var canvas,ctx;
const onload = () =>{
canvas = document.querySelector("#canvas")
ctx = canvas.getContext('2d')
drawLine("#ff0000")
drawLine("#ffffff")
}
const drawLine = (color) =>{
ctx.beginPath()
ctx.strokeStyle = color
ctx.moveTo(0,0)
ctx.lineTo(200,200)
ctx.stroke()
ctx.closePath()
}
<!DOCTYPE html>
<head>
<script src="scripts.js" type="text/javascript"></script>
</head>
<html>
<body onload = "onload()">
<canvas id = "canvas" style="border: solid 1px; width: 200px; height: 200px;"></canvas>
</body>
</html>

Canvas duplicates multiple shapes

I want to add 10 to the position of the ball, but it adds position to the duplicated shape. I tried to make a separate function but it did not work.
HTML5 Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="Game" width="800" height="600" style="border: 1px solid #d3d3d3;
background-color: #f1f1f1;"></canvas>
<script src="Game.js"></script>
</body>
</html>
Javascript Code:
var GameCanvas = GameCanvas = document.getElementById("Game");
var GameCtx = GameCtx = GameCanvas.getContext("2d");;
var BallSprite = 50;
window.onload = function () {
setInterval(HoldSprites, 100);
}
function HoldSprites() {
BallSprite = BallSprite + 10;
GameCtx.beginPath();
GameCtx.arc(BallSprite, 50, 40, 0, 2 * Math.PI);
GameCtx.stroke();
}

Line drawing not showing on Canvas

I am trying to draw a simple line on but it doesn't work on the page. I have placed my JavaScript in several places on the html page, but it still doesn't work.
Does anyone know what I did wrong?
Thank you
My JavaScript code:
function drawLine() {
var c = document.getElementById("line");
var draw = c.getContext("2d");
draw.beginPath();
draw.lineWidth("5");
draw.strokeStyle("blue");
draw.moveTo(0, 75);
draw.lineTo(0, 75);
draw.stroke();
}
My Html code:
<!DOCTYPE html>
<html lang="eng">
<script type="text/javascript" src="vhw.js"></script>
</head>
<body>
<script type="text/javascript" src="vhw.js"></script>
<!-- INTRODUCTION -->
<div>
<h1 class="intro">
Line
</h1>
</div>
<!-- LINE CODE -->
<div class="space">
<canvas id="line" width="500" height="300" style="border: 2px dotted #990099; display: block; margin-right: auto; margin-left: auto;" onload="drawLine()">
</canvas>
</div>
</body>
</html>
call drawLine methode from onload of window not from canvas element :
window.onload = function(e){
drawLine();
}
and your html code like this :
<div class="space">
<canvas id="line" width="300" height="150" style="border: 2px dotted #990099;
display: block; margin-right: auto; margin-left: auto;" >
</canvas>
</div>
also your drawLine :
function drawLine() {
var canevas = document.getElementById('line');
if (canevas.getContext) {
var c = document.getElementById("line");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(300, 150);
ctx.stroke();
}
}

How to change canvas image on click?

I am trying to change the image of canvas on click according to count of click being even or odd.
Basically i want to make a zero and cross game in which image on canvas changes to a cross or zero depending upon the count of mouse click.How to track count of click on canvas? Please help.
Please guide me as i am a beginner in html.
<!DOCTYPE html>
<head>
<title> samp1 </title>
</head>
<body>
<canvas id="mycanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<style>
#mycanvas {
margin-top:10px;
margin-left:10px;
}
</style>
<img src="http://images.all-free- download.com/images/graphicthumb/roses_554954.jpg" id="my" width="200" height="100"/>
<img src="http://images.all-free-download.com/images/graphicthumb/flower_lighting_554944.jpg" id="ny" width="200" height="100"/>
<script>
var i=0;
function fn(){
if(i%2==0)
ctx.drawImage(im,0,0,can.width,can.height);
else
ctx.drawImage(in,0,0,can.width,can.height);
i++;}
var can = document.getElementById("mycanvas");
var ctx = can.getContext("2d");
var im=document.getElementById("my");
var in=document.getElementById("ny");
can.addEventListener("click", fn, false);
</script>
</body>
</html>
I see 2 very small errors:
'in' is a reserved word in javascript.
you have a space in the URL for the 'my' img element
With those corrected your codes should work the way you want.
Here is a fiddle to demonstrate:
http://jsfiddle.net/w09tyftt/1/
<style>
#mycanvas {
margin-top:10px;
margin-left:10px;
}
</style>
<canvas id="mycanvas" width="200" height="100" style="border:1px solid #000000;">
<img src="http://images.all-free-download.com/images/graphicthumb/roses_554954.jpg" id="my" width="200" height="100" />
<img src="http://images.all-free-download.com/images/graphicthumb/flower_lighting_554944.jpg" id="ny" width="200" height="100" />
<script>
var i = 0;
function fn() {
if (i % 2 == 0) ctx.drawImage(im, 0, 0, can.width, can.height);
else ctx.drawImage(vin, 0, 0, can.width, can.height);
i++;
}
var can = document.getElementById("mycanvas");
var ctx = can.getContext("2d");
var im = document.getElementById("my");
var vin = document.getElementById("ny");
can.addEventListener("click", fn, false);
</script>

Using destination-over to save background and actual sketch

I've read this and a few other questions, and it is clear I need to use destination-over to save the background and the sketch by display the new image over the old one.
I'm using Sketch.JS with my code as such:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
$('#myCanvas').sketch({
defaultColor: "red"
});
$('#download').click(function() {
ctx.globalCompositeOperation = "destination-over";
img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = 'http://lorempixel.com/400/200/';
ctx.drawImage(img, 0, 0);
$('#url').text(c.toDataURL('/image/png'));
window.open(c.toDataURL('/image/png'));
});
#myCanvas {
background: url(http://lorempixel.com/400/200/);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/intridea/sketch.js/gh-pages/lib/sketch.js"></script>
<canvas id="myCanvas"></canvas>
<input type='button' id='download' value='download'>
<span id='url'></span>
Fiddle
But that doesn't help. Clicking 'download' still only produces the sketch. Now, it seems I don't understand how I need to use destination-over properly. W3Schools doesn't seem to help.
Could anyone point me in the right direction please?
Assume you have a SketchJS canvas on top of an image containing a background:
#wrapper{positon:relative;}
#bk,#myCanvas{position:absolute;}
<div id='wrapper'>
<img crossOrigin='anonymous' id=bk src='yourImage.png'>
<canvas id="myCanvas" width=500 height=300></canvas>
</div>
Then when you want to combine the Sketch with the background and save it as an image you can use destination-over compositing to draw the background "under" the existing Sketch.
ctx.globalCompositeOperation='destination-over';
ctx.drawImage(bk, 0, 0);
Here's example code:
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://rawgit.com/intridea/sketch.js/gh-pages/lib/sketch.js"></script>
<style>
body{ background-color: ivory; }
#wrapper{positon:relative;}
#bk,#myCanvas{position:absolute;}
</style>
<script>
$(function(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
$('#myCanvas').sketch({ defaultColor: "red" });
$('#download').click(function() {
var img=document.getElementById('bk');
ctx.globalCompositeOperation='destination-over';
ctx.drawImage(bk, 0, 0);
ctx.globalCompositeOperation='source-over';
var html="<p>Right-click on image below and Save-Picture-As</p>";
html+="<img src='"+c.toDataURL()+"' alt='from canvas'/>";
var tab=window.open();
tab.document.write(html);
});
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag to sketch on the map.</h4>
<button id=download>Download</button>
<div id='wrapper'>
<img crossOrigin='anonymous' id=bk src='https://dl.dropboxusercontent.com/u/139992952/multple/googlemap1.png'>
<canvas id="myCanvas" width=459 height=459></canvas>
</div>
</body>
</html>

Categories

Resources