Image width in canvas isnt being displayed correctly - javascript

I have this canvas I'm drawing onto. And I want to make image to be placed in the left lower corner.
var canvasWidth = 800;
var canvasHeight = 600;
$("#gameCanvas").attr("width", canvasWidth);
$("#gameCanvas").attr("height", canvasHeight);
var canvas = $("#gameCanvas")[0].getContext("2d");
var image = new Image();
image.src="you.png";
var player1X =0;
var imageHeight=image.height;
var player1Y = canvasHeight - imageHeight;
canvas.rect(0, 0, canvasWidth, canvasHeight);
canvas.fillStyle="#5c7792";
canvas.fill();
$(image).load(function(){
canvas.drawImage(image, player1X , player1Y);
});
but the problem is that when I use variable player1Y, it results in image being displayed at coordinates (0, canvasHeight). Actually, it results in image not being shown. But when I write canvas.drawImage(image, player1X, canvasHeight - image.height) it works perfectly.
How do I make the variable to control the posiotion of image?
Here is JSfiddle: http://jsfiddle.net/u9Ehs/10/

The problem is that the image hasn't fully loaded when you are setting imageHeight & player1Y.
Refactor your code to set all image related variables inside image.onload:
Example code and a Demo: http://jsfiddle.net/m1erickson/CSQGh/
<!doctype html>
<html>
<head>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
window.onload = function() {
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var player1X=0;
var player1Y;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/ship.png";
function start(){
player1Y=canvas.height-img.height;
ctx.drawImage(img,player1X,player1Y);
}
}; // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Related

Draw image with button

hi i am trying to draw image with a button in canvas. But i can not draw in the clear canvas. so;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Başlıksız Belge</title>
</head>
<body>
<input type="button" id="b1" value="ciz">
<canvas id="canvas" height="300" width="600" style="border: solid;background-color: brown; " >Eski Sürüm Tarayıcı . </canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var b1 =document.getElementById("b1");
var image = new Image(60, 45); // using optional size for image
var kontrol;
image.src = '/pika.png'; //it is in my pc
image.onload = function(){ // i don't want draw the image on load
kontrol=true;}
b1.onclick=function(){ // i want draw with button
if(kontrol=true){
ctx.drawImage(image, 0, 0);
}
}
</script>
</body>
</html>
when i try with image on load function it is working but i want draw with the button
No problem i get it. thanks...
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var b1 =document.getElementById("b1");
var image = new Image(60, 45);
b1.onclick=function(){
image.src = 'https://i.hizliresim.com/nWdGrR.png';
image.onload = function(){
ctx.drawImage(image, 0, 0);
}
}
If pika.png is located in same directory as your html file then just remove the forward slash before your image's name: image.src = 'pika.png';

Draw on Image loaded inside HTML canvas

I have a HTML canvas in Ionic app.
<canvas id="canvas" color="{{ color }}" width="800" height="600" style="position:relative;"></canvas>
In this canvas, I am loading an image. Below is the code from controller
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = $stateParams.imageId;
img.onload = function() {
context.drawImage(img, 0, 0, canvas.width, canvas.height);
}
After the image is loaded, users need the ability to write on the image and circle/highlight certain areas of the image.
Doesn't HTML canvas provide this feature by default? Right now I am not able to annotate anything on the image. How can I achieve this?
You need to implement this yourself.
You can do it by hooking into the mouse click / move events. using your 2d context, draw small rectangle at the mouse's current position if the most moves and the left mouse button is down.
The effect is similar to a Windows paint pencil tool. Here's a simple example.
<html>
<head>
<style>
canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var isMouseDown = false;
canvas.onmousedown = function(e){
isMouseDown = true;
}
canvas.onmouseup = function(e){
isMouseDown = false;
}
canvas.onmousemove = function(e){
if(isMouseDown === false){
return;
}
var canvasPosition = canvas.getBoundingClientRect();
var x = e.clientX - canvasPosition.left;
var y = e.clientY - canvasPosition.top;
ctx.fillRect(x, y, 2, 2);
};
</script>
</body>
</html>

Canvas DrawImage() poor quality [duplicate]

This question already has answers here:
Html5 canvas drawImage: how to apply antialiasing
(6 answers)
Closed 8 years ago.
I have a problem with Html5 canvas
i draw an image but its quality becomes very poor
after i draw it with canvas it becomes this
my code is here
<script type="text/javascript">
$canvasWidth = $('#canvas').width;
$canvasHeight = $('#canvas').height;
var alpha = 0.0;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function draw(){
var delta = 0.05;
ctx.clearRect(0,0,$canvasWidth, $canvasHeight);
ctx.globalAlpha = alpha;
var logo= new Image();
WandioLight.onload = function(){
ctx.drawImage(logo, 0, 0, 250, 167);
};
logo.src = "logo.png";
alpha += delta;
if(alpha > 1.0){
return false;
}
setTimeout(draw, 50);
}
You can incrementally scale your image down for better results.
Since your final size is 1/4 the original size, you could:
scale the 1000x669 image in half to 500x334 onto a temp canvas
scale the 500x335 canvas in half to 250x167 onto the main canvas
Here's example code and a Demo:
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://ictcluster.ge/wp-content/uploads/2018/09/wandio-logo-1-1024x724.png";
function start(){
// scale the 1000x669 image in half to 500x334 onto a temp canvas
var c1=scaleIt(img,0.50);
// scale the 500x335 canvas in half to 250x167 onto the main canvas
canvas.width=c1.width/2;
canvas.height=c1.height/2;
ctx.drawImage(c1,0,0,250,167);
}
function scaleIt(source,scaleFactor){
var c=document.createElement('canvas');
var ctx=c.getContext('2d');
var w=source.width*scaleFactor;
var h=source.height*scaleFactor;
c.width=w;
c.height=h;
ctx.drawImage(source,0,0,w,h);
return(c);
}
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

rotating 2 images on canvas

I have to draw 3 images on the canvas and need to rotate 2 of the images.
The images are like
1. circular with a vertical straight line
2. just an horizontal line
3. Big circular image
I need to rotate the 1st 2 images in the center of the canvas.
var canvas = document.getElementById('NewImage');
var context = canvas.getContext('2d');
context.canvas.width = window.innerWidth;
context.canvas.height = window.innerHeight*0.7;
var imageObj = new Image();
var imageObj2 = new Image();
var imageObj3 = new Image();
imageObj.onload = function() {
context.save();
context.translate(imageObj.width/2,imageObj.height/2);
context.rotate(-10*Math.PI/180);
//context.translate(-imageObj.width/2,-imageObj.height/2);
context.drawImage(imageObj,-(imageObj.width/2),-(imageObj.height/2),context.canvas.width,context.canvas.height*0.85);
context.restore();
context.save();
context.globalCompositeOperation="source-over";
context.translate(imageObj2.width/2,imageObj2.height/2);
context.rotate(-10*Math.PI/180);
context.translate(-imageObj2.width/2,-imageObj2.height/2);
context.drawImage(imageObj2, x, y,context.canvas.width,6);
context.restore();
//context.rotate(10*Math.PI/180);
context.drawImage(imageObj3, 0, 0,context.canvas.width,context.canvas.height*0.9);
};
imageObj.src = 'canvas/inner_circle_blackline_vertical.png';
imageObj2.src = 'canvas/horizontal.png';
imageObj3.src = 'canvas/outer_circle.png';
When i try to rotate, the images are not rotating in center. when 1st 2 images rotates it has to look like "X" symbol.
How will i rotate in center of the canvas.
Thanks:)
As designed, your imageObj2 and imageObj3 will never load.
Here is a generic image loader that will load all your images and store them in an array called imgs[].
When all your images have fully loaded, the render() function will be called. That’s where you start drawing.
// This is an image loader
// When render() is called, all your images are fully loaded
var imgURLs = [
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png"];
var imgs=[];
var imgCount=0;
pre_load();
function pre_load(){
for(var i=0;i<imgURLs.length;i++){
var img=new Image();
imgs.push(img);
img.onload=function(){
if(++imgCount>=imgs.length){
// images are now fully loaded
render();
}
}
img.src=imgURLs[i];
}
}
In render(), you just draw your images.
Since the same action (rotating an image) is done repeatedly, you can create a helper function to do the rotated drawing. Here the helper function is drawImageAtAngle.
// draw the rotated lines on the canvas
function render(){
var x=canvas.width/2;
var y=canvas.height/2;
drawImageAtAngle(imgs[0],x,y,-45);
drawImageAtAngle(imgs[2],x,y,45);
drawImageAtAngle(imgs[1],x,y,0);
}
Here the helper function that rotates a supplied image to a supplied angle:
function drawImageAtAngle(image,X,Y,degrees){
var radians=degrees*Math.PI/180;
var halfWidth=image.width/2;
var halfHeight=image.height/2;
ctx.beginPath();
ctx.save();
ctx.translate(X,Y);
ctx.rotate(radians);
ctx.drawImage(image,-halfWidth,-halfHeight);
ctx.restore();
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/ZShWW/
<!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; padding:10px;}
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// This is an image loader
// When render() is called, all your images are fully loaded
var imgURLs = [
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png",
"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png"];
var imgs=[];
var imgCount=0;
pre_load();
function pre_load(){
for(var i=0;i<imgURLs.length;i++){
var img=new Image();
imgs.push(img);
img.onload=function(){
if(++imgCount>=imgs.length){
// images are now fully loaded
render();
}
}
img.src=imgURLs[i];
}
}
// draw the rotated lines on the canvas
function render(){
var x=canvas.width/2;
var y=canvas.height/2;
drawImageAtAngle(imgs[0],x,y,-45);
drawImageAtAngle(imgs[2],x,y,45);
drawImageAtAngle(imgs[1],x,y,0);
}
function drawImageAtAngle(image,X,Y,degrees){
var radians=degrees*Math.PI/180;
var halfWidth=image.width/2;
var halfHeight=image.height/2;
ctx.beginPath();
ctx.save();
ctx.translate(X,Y);
ctx.rotate(radians);
ctx.drawImage(image,-halfWidth,-halfHeight);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<p>This is the line image</p>
<img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/line.png">
<p>The line image rotated at center of canvas</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
To find the center of the canvas you have to use the dimensions of the canvas. In your code you are using the dimensions of the image. That is, this line:
context.translate(imageObj.width/2,imageObj.height/2);
should probably be:
context.translate(canvas.width/2,canvas.height/2);
That moves you to the center of the canvas. The rotation then occurs around that center. You are then drawing the image centered on the origin. That part looks correct.
You will then reverse the rotation and then the translation.

HTML5 canvas can't apply sw filter

I want to write code that can filter the source of an image and return the data that it can be used as source for an image tag in the DOM. Therfore I created a virtual canvas. At the moment it only works with a real canvas within the DOM, even though the dimension is wrong. I only want the converted image source and no canvas in the DOM.
this is how I need it but it doesn't work: js fiddle
this one works with wrong img dimension and unwanted canvas in the DOM: js fiddle2
js:
var image = new Image();
image.onload = function () {
var helperCanvas = document.createElement('canvas');
var ctx = helperCanvas.getContext('2d');
ctx.width = image.width;
ctx.height = image.height;
ctx.drawImage(image, 0, 0, helperCanvas.width, helperCanvas.height);
var imageData = ctx.getImageData(0, 0, helperCanvas.width, helperCanvas.height);
filter(imageData);
data_as_source = ctx.putImageData(imageData, 0, 0 ).toURL();
var img = new Image();
img.src = data_as_source;
context.drawImage(img,0,0);
}
image.src = ....
In your demo code, you should be changing the temporary canvas width/height, not the context’s.
helperCanvas.width = image.width;
helperCanvas.height = image.height;
Here is code with a test filter that just turns all non-transparent pixels red.
It also renders the filtered canvas image to an image on the page.
BTW, when creating an image object, there is a new Chrome bug that can be avoided if you create like this:
var img=document.createElement("img");
Fiddle that must be viewed in Chrome or FF (IE==CORS failure): http://jsfiddle.net/m1erickson/LeGD5/
Here is code:
<!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.createElement("canvas");
var ctx=canvas.getContext("2d");
var img=document.createElement("img");
img.onload=function(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0,img.width,img.height);
// test -- turn every non-transparent pixel red
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var pixels = imgData.data; // get pixel data
for (var i = 0; i < pixels.length; i +=4)
{
// if this pixel is not transparent,
// mask it in pure red
if(pixels[i+3]>0){
pixels[i]=255; // this is the red component of the pixel
pixels[i+1]=0; // this is the green component of the pixel
pixels[i+2]=0; // this is the blue component of the pixel
pixels[i+3]=255; // this is the alpha component of the pixel
}
}
ctx.putImageData(imgData, 0, 0);
var theImage=document.getElementById("theImage");
theImage.src=canvas.toDataURL();
}
img.crossOrigin="anonymous";
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png";
}); // end $(function(){});
</script>
</head>
<body>
<img id="theImage" width=300 height=300>
</body>
</html>
you had a couple bugs in your dataURL part, but this seems to work:
var image = new Image();
image.onload = function () {
var helperCanvas = document.createElement('canvas');
var ctx = helperCanvas.getContext('2d');
ctx.width = image.width;
ctx.height = image.height;
ctx.drawImage(image, 0, 0, helperCanvas.width, helperCanvas.height);
var imageData = ctx.getImageData(0, 0, helperCanvas.width, helperCanvas.height);
filter(imageData);
ctx.putImageData(imageData, 0, 0 );
//context.drawImage(img,0,0);
data_as_source = helperCanvas.toDataURL();
var img = new Image();
img.src = data_as_source;
img.style.border="3px solid red";// for demo sake
document.body.appendChild(img); // for demo sake
}

Categories

Resources