Why is this appearing behind the canvas instead of drawing over it? - javascript

I am working on a dynamic web map with HTML5 and canvas.
I loaded the map in PNG format, but whenever I try to draw on it, it draws behind the map like this:
I need it to draw over the white squares.
This is my code:
window.onload = function() {
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "img/plano.png"; //transparent png
ctx.fillRect(1039, 150, 50, 50);
}
Thanks in advance!

The fillRect needs to happen after the image has loaded. The image loads asynchronously so the only safe place for this to happen is after the drawImage...
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.fillRect(200,200,50,50); // Draw rect after image
}

Related

How can I get full image after zooming in canvas

I am facing this issue where once I zoom in on some image in the canvas in javascript, some part of the image goes outside of the canvas. Then I am drawing something on it. But now, I want the latest total image instead of just what is on the canvas frame. How can I get that?
Here is my code for it. Whenever a scroll-up or scroll-down happens, the below function gets called.
var zoom = function(clicks)
{
original = canvas.toDataURL();
// clear the canvas
var p1 = ctx.transformedPoint(0,0);
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
// translate the image according to zoom factor and location of zoom
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x,pt.y);
var factor = Math.pow(scaleFactor,clicks);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);
// draw te image on canvas
const img = document.createElement("img");
img.setAttribute("src", original);
img.onload = function () {
ctx.drawImage( img, 0, 0, canvas.width, canvas.height);
};
}

JavaScript Image not drawing to canvas

I am just being a complete noob and been looking around for a answer. "ctx.fillRect(0,0,100,100);" works which mean ctx was declared correctly and "test()" is being called. I just don't understand why the image wont draw.
var Img = new Image();
Img.scr ='/client/Assets/StartScreen/Background.png'; //This URL was tested via html img tag
function test(){
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,100,100); //THIS WORKS
ctx.drawImage(Img,0,0,600,600); // Will not load
}
Img.scr ='/client/Assets/StartScreen/Background.png'; //This URL was tested via html img tag
Img.scr undefined property. You should try with Img.src
Img.src ='/client/Assets/StartScreen/Background.png';
Two things:
Your code had img.scr, not img.src.
Image loading happens asynchronously; you'll need to wait for the image to be complete (img.complete). You can use the onload event listener to draw things the instant the image is ready.
var img = new Image();
img.src = "/client/Assets/StartScreen/Background.png";
function draw() {
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 100, 100);
ctx.drawImage(img, 0, 0, 600, 600);
}
img.onload = function() {
draw();
};
You should add image to canvas only when it is loaded.
try,
var Img = new Image();
Img.src ='/client/Assets/StartScreen/Background.png';
Img.onload = function() {
test();
}
function test(){
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,100,100);
ctx.drawImage(Img,0,0,600,600);
}

Draw a square version of image in canvas

I am trying to show previews of uploaded images in a canvas. The preview should be a square version of image.
What I have:
var img = new Image;
img.src = imageSrc;
var c = document.getElementById('file-preview-' + data.response.id);
var ctx = c.getContext("2d");
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
And the preview:
So how can I draw on the canvas a 150x150 square with maintained ratio cropped version of the image?
For example for this image:
I should get:
Here's a method that yields precisely the result you desire, cropped, resized and centered (with commented out lines that yield a left based cropping instead)...
var ctx;
function init(event) {
ctx = document.getElementById('canvas').getContext('2d');
// Your preview is actually 120x120,
// but I've stuck with the textual description of
// your requirements here.
ctx.canvas.width = 150;
ctx.canvas.height = 150;
loadBackground('http://i.stack.imgur.com/PCKEo.png');
}
function loadBackground(path) {
var img = new Image();
img.onload = drawBackground;
img.src = path;
}
function drawBackground(event) {
var img = event.target;
var imgSize = Math.min(img.width, img.height);
// The following two lines yield a central based cropping.
// They can both be amended to be 0, if you wish it to be
// a left based cropped image.
var left = (img.width - imgSize) / 2;
var top = (img.height - imgSize) / 2;
//var left = 0; // If you wish left based cropping instead.
//var top = 0; // If you wish left based cropping instead.
ctx.drawImage(event.target, left, top, imgSize, imgSize, 0, 0, ctx.canvas.width, ctx.canvas.height);
}
window.addEventListener('load', init, false);
<canvas id="canvas"></canvas>
Based on information from this question: SO Question
I was able to modify what was done to create a square cropped image in canvas:
var img = new Image;
img.src = "http://cdn.bmwblog.com/wp-content/uploads/2016/02/M-Performance-Parts-BMW-M2-3.jpg"; //Or whatever image source you have
var c= document.getElementById('file-preview');
var ctx=c.getContext("2d");
img.onload = function(){
ctx.drawImage(img, img.width/2, img.height/2, img.width, img.height, 0, 0, img.width, img.height);
};
You just have to modify the arguments you are passing to the drawImage function as well as add some more.
You can see a fiddle here: https://jsfiddle.net/4d93pkoa/3/
Remember that the first two parameters specify the image's top left coordinates within the canvas element.
Remember to set the width and height of the canvas element in HTML to a square shape.

Drawing another image to canvas

So I am creating a cordova app where I take a photo from the iphone library, draw it to canvas and add another image to it in order to save it as one photo. So far the photo I draw from the iphone photo library gets drawn without problems to the canvas, however the second image doesn't.
When I load the second image, it first gets added to a div with absolute positioning in order to move it to wherever I want. After that I get the actual image it's source and it's positions and try to draw it to canvas. The drawing of the second image happens when I call a method that also performs the canvas2ImagePlugin it's functions. In the end only the first photo without the second image gets saved.
The draw image to canvas function:
function drawImage(image_source, dx, dy)
{
var canvas = document.getElementById('Photo');
var image = new Image();
image.src = image_source;
image.onload = function() {
c=canvas.getContext("2d");
c.canvas.width = window.innerWidth;
c.canvas.height = window.innerHeight;
c.drawImage(image,dx,dy, window.innerWidth, window.innerHeight);
}
}
The method for drawing the second image and saving it:
function saveImage()
{
var img = $('.ObjectImage').attr('src', $('img:first').attr('src'));
var imagePosition = $('.ObjectImage').find('img:first').position();
drawImage(img, imgPosition.left, imgPosition.top);
window.canvas2ImagePlugin.saveImageDataToLibrary(
function(msg){
console.log(msg);
},
function(err){
console.log(err);
},
document.getElementById('Photo')
);
alert("Image saved");
}
The window.innerWidth, window.innerHeight on the canvas is done to get the canvas in full screen of the parent div.
EDIT to the comment:
function drawImage(image_source, dx, dy)
{
var canvas = document.getElementById('Photo');
var image = new Image();
image.onload = function() {
c=canvas.getContext("2d");
c.canvas.width = window.innerWidth;
c.canvas.height = window.innerHeight;
c.drawImage(image,dx,dy, window.innerWidth, window.innerHeight);
}
image.src = image_source;
}
Still not working
The drawImage function works asynchronously, it starts loading an image and exits immediately. Then, when the image loads, the canvas is updated. If you run something like:
drawImage('test.jpg',0,0);
drawImage('test2.jpg',0,0);
you will get both images updating the canvas at approximately the same time and only one will appear.
Also, what wolfhammer said is correct. If you set the size of the canvas, you clear it, so drawing one image after the other, even if they are smaller sizes and should both appear, will only show the last one. Check this link on how to solve it: Preventing Canvas Clear when Resizing Window
Further more, you are drawing all images with the width and height of the window, which doesn't make sense. Probably you want to use the width and height of the image (so this.width instead of window.innerWidth)
When you set the width and height of the canvas the data on "Photo" is cleared. I've provide a resize function if resizing is really needed.
function drawImage(image_source, dx, dy)
{
var canvas = document.getElementById('Photo');
var image = new Image();
image.src = image_source;
image.onload = function() {
c=canvas.getContext("2d");
//c.canvas.width = window.innerWidth;
//c.canvas.height = window.innerHeight;
c.drawImage(image,dx,dy, window.innerWidth, window.innerHeight);
}
}
var can = document.getElementById('can');
var ctx = can.getContext('2d');
ctx.fillStyle = "red";
ctx.beginPath();
ctx.moveTo(20, 90);
ctx.lineTo(50, 10);
ctx.lineTo(80, 90);
ctx.lineTo(10, 40);
ctx.lineTo(90, 40);
ctx.lineTo(20, 90);
ctx.fill();
var btn = document.getElementById('btnResize');
btn.addEventListener('click', function() {
resize(can, can.width * 2, can.height * 2);
});
function resize(can, w, h) {
var ctx = can.getContext('2d');
// copy
var can2 = document.createElement('canvas');
var ctx2 = can2.getContext('2d');
can2.width = can.width;
can2.height = can.height;
ctx2.drawImage(can, 0, 0);
// resize
can.width = w;
can.height = h;
ctx.drawImage(can2, 0, 0, can2.width, can2.height, 0, 0, w, h);
}
#can {
border:1px solid red;
}
<button id='btnResize'>Size x 2</button><br/>
<canvas id="can" width="100" height="100"></canvas>

Overlay visible areas of transparent black silhouette PNG with pattern using CSS3 or JS

I'm looking for a way to overlay the visible areas of a transparent black silhouette PNG file with a certain pattern.
Is there a CSS, JavaScript, mixed solution for this?
Example: I have one image of a weapon silhoutte and a set of camo patterns which I want to lay over the weapon.
Demo: In Photoshop the same result is givin when selecting layer mask > overlay.
Ps: my question is similar to this thread: Silhouette a PNG image using CSS except I am looking for the exact opposite.
You can do this using canvas with globalCompositeOperation set to destination-in. For example
var canvas = document.createElement('canvas');
canvas.width = 250;
canvas.height = 250;
var canvas_context = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
var msk = new Image();
msk.onload = function(){
canvas_context.drawImage(img, 0, 0);
canvas_context.globalCompositeOperation = "destination-in";
canvas_context.drawImage(msk, 0, 0);
canvas_context.globalCompositeOperation = "source-over";
};
msk.src = 'silhouette.png';
}
img.src = 'pattern.jpg';
document.body.appendChild(canvas);

Categories

Resources