Black canvas instead of image - javascript

I have a problem with canvas. Let's say, 1/10 time I have black square instead of my image, on chrome. My code is as follow, how can I modify it in order to avoid this black display?
<canvas id="Canvas" width="954" height="267"></canvas>
<script>
var canvas = document.getElementById('Canvas');
var context = canvas.getContext("2d");
// Map sprite
var mapSprite = new Image();
mapSprite.src = 'image.png';
var main = function () {
draw();
};
var draw = function () {
// Clear Canvas
context.fillStyle = "#000";
context.fillRect(0, 0, canvas.width, canvas.height);
// Draw diagramme
context.drawImage(mapSprite, 0, 0, 954, 267);
}
main();
</script>
EDIT 1: full function draw :
var draw = function () {
// Clear Canvas
context.fillStyle = "#000";
context.fillRect(0, 0, canvas.width, canvas.height);
// Draw diagramme
context.drawImage(mapSprite, 0, 0, nextWidth, nextHeight);
//draw all precedent cross
cross = new Image();
cross.src = "cross.png";
for (var i = 0; i < array_x.length; i++) {
context.drawImage(cross, array_x[i], array_y[i], 10, 10);
}
}

I believe you want to wait until image is loaded.
Replace:
main();
With:
mapSprite.addEventListener('load', main);

Related

Render video with HTML Canvas in red and black&white colors

I need to render a video with HTML Canvas in red color. Code Below (if doesn't work, try here codepen code). This code add red layer, but I need in first place - desaturate, after reduce brightness and only then add red layer. I tried work with pixels (problems with perfomance), ctx.filter doesnt work either.
const URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
const video = document.createElement('video');
navigator.mediaDevices.getUserMedia({
audio: true,
video: true,
}).then((stream) => {
video.src = URL.createObjectURL(stream);
});
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const loop = () => {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(255, 0, 0, .45)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(loop);
};
loop();
<canvas id="canvas" width="400" height="400"></canvas>
You can use multiply blending mode to knock out the other colors channels. Since you only define red the other channels with be multiplied with 0, leaving them "empty".
Just remember to reset composite mode to "source-over" before drawing the next video frame.
var img = new Image(); img.onload = draw; img.src = "//i.imgur.com/Kzz84cr.png";
function draw() {
c.width = this.width; c.height = this.height;
var ctx = c.getContext("2d");
// main loop
ctx.drawImage(this, 0, 0); // draw video frame
ctx.globalCompositeOperation = "multiply"; // change blending mode
ctx.fillStyle = "red"; // draw red on top
ctx.fillRect(0, 0, c.width, c.height);
ctx.globalCompositeOperation = "source-over"; // "reset"
// rinse, repeat
}
<canvas id=c></canvas>

How to put image in to circle canvas?

>>> Jsfiddle
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(55,95,30,0,2*Math.PI);
ctx.stroke();
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src='https://www.gravatar.com/avatar/4af2cdbaf02d97ba88d5d6daff94fbae/?default=&s=80';
base_image.onload = function(){
context.drawImage(base_image, 20, 20);
}
}
<canvas id="myCanvas"
width="236"
height="413"
style="border:1px solid #000000;
position:absolute;
top:66px;
left:22px;"></canvas>
I have try to put the image in to canvas instead my circle position.
but i don't know how to resize square image to circle with same size of my draw circle and put in to the same position.
What should i do?
You have to use clip for this.
Here is Codepen for this http://codepen.io/sam83045/pen/eBKRPr?editors=0010
And your edited javascript code is as follows :
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(55, 95, 30, 0, 2 * Math.PI);
ctx.clip();
ctx.stroke();
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');
make_base();
function make_base() {
base_image = new Image();
base_image.src = 'https://www.gravatar.com/avatar/4af2cdbaf02d97ba88d5d6daff94fbae/?default=&s=80';
base_image.onload = function() {
context.drawImage(base_image, 16, 55);
}
}
window.onload=function(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.addEventListener("click",function(){
ctx.clearRect(0, 0, c.width, c.height);
var object = images.shift();
images.push(object);
create(ctx);
},false)
var loaded=0;
var error=0;
var images=new Array
(
{
image:null,
url:"https://www.gravatar.com/avatar/4af2cdbaf02d97ba88d5d6daff94fbae/?s=80",
expandW:0,
expandH:0,
clip:false,
visible:true,
shape:
{
x:0,
y:0,
rect:
{
w:30,
h:50
},
boundary:
function(){return {w:this.rect.w,h:this.rect.h,centerX:this.rect.w/2,centerY:this.rect.h/2};}
}
},
{
image:null,
url:"http://iconbug.com/data/7c/512/6e1cd685219a18b951b191ad04407324.png",
expandW:0,
expandH:0,
clip:true,
visible:true,
shape:
{
x:30,
y:30,
circle:
{
r:30
},
boundary:
function(){return {w:this.circle.r*2,h:this.circle.r*2,centerX:0,centerY:0};}
}
}
);
function loadImages(ctx)
{
for (var i=0;i<images.length;i++)
{
images[i].image= new Image();
images[i].image.src = images[i].url;
images[i].image.onerror=function(){
loaded++;
error++;
loadedText(images.length,loaded,error);
if(loaded===images.length)
{
create(ctx);
}
};
images[i].image.onload=function(){
loaded++;
loadedText(images.length,loaded,error);
if(loaded===images.length)
{
create(ctx);
}
};
}
}
function loadedText(sum,count,error)
{
if(error)
console.log((count-error)+" images loaded from "+count+"."+error+" images not loaded.");
else
console.log(count+" images loaded from "+count+".");
}
function create(ctx)
{
for (var i=0;i<images.length;i++)
{
ctx.save();
if(images[i].image !==null && images[i].visible)
{
var object=images[i];
var boundary=object.shape.boundary();
var image=object.image;
var shape=object.shape;
if(shape.circle)
{
drawCircle(
shape.x,
shape.y,
shape.circle.r,
ctx,
object.clip
);
}
if(shape.rect)
{
drawRect(
shape.x,
shape.y,
shape.rect.w,
shape.rect.h,
ctx,
object.clip
);
}
if(!object.clip)
{
image.width=image.width*(boundary.w/image.width);
image.height=image.height*(boundary.h/image.height);
}
image.width=image.width+object.expandW;
image.height=image.height+object.expandH;
var x=(shape.x+boundary.centerX)-image.width/2;
var y=(shape.y+boundary.centerY)-image.height/2;
ctx.drawImage(image, x, y,image.width,image.height);
}
ctx.restore();
}
}
function drawCircle(x,y,r,ctx,clip){
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI);
if(clip)
{
ctx.clip();
}
ctx.stroke();
}
function drawRect(x,y,w,h,ctx,clip){
ctx.beginPath();
ctx.rect(x, y, w, h);
if(clip)
{
ctx.clip();
}
ctx.stroke();
}
loadImages(ctx);
};
Add multiple images.
If you do not have many pictures, it is easier to load them at once.
On console (F12) you can see load progress.
Every image has is own options.
image- it will populated latter
url- address
expandW, expandH- you can manipulate Picture after clipping.
clip- do we make picture size of image or we clip shape from image.
visible- do we show image.
shape-clipping shape
shape options
x,y-position of shape
rect or circle type of shape.
boundary- we get shape centre position and shape with and height. (circle with and height is actually double of radius).
with mouse click on canvas you can cycle through all loaded pictures.

Javascript Canvas clear/ redraw

I've tried googling the answer to this but i'm just going around in circles....
If I clear the rect (using clearRect) then the image doesn't redraw after.
However, if I don't clear the images just stack.
What I want it to clear the current image and then draw with new one.
What am I missing?
Does it have something to do with the image Load ?
Sorry if this is a question repeat, I couldn't find the exact answer to this- and I tried what others suggested but results were poor.
http://jsfiddle.net/bxeuhh4h/
function clear() {
var canvasTemp = document.getElementById(imgSection);
var ctxTemp = canvasTemp.getContext("2d");
ctxTemp.clearRect(0, 0, 500, 500);
}
function fillColorOrPattern(imgSection,currentcolor){
if ((oldcolor !== currentcolor) || (oldxImgToBeFilled !== xImgToBeFilled)){
clear();
}
imgFill.onload = function () {
imgToBeFilled.onload = function () {
if ((oldcolor !== currentcolor) || (oldxImgToBeFilled !== xImgToBeFilled)){
fill(imgSection,currentcolor)
}
};
imgToBeFilled.src = xImgToBeFilled;
}
imgFill.src = xImgFill;
}
function fill(imgSection,currentcolor){
canvas = document.getElementById(imgSection);
ctx = canvas.getContext("2d");
ctx.drawImage(imgToBeFilled, 0, 0);
ctx.globalCompositeOperation = "source-atop";
console.log(isItColorOrPattern);
if (isItColorOrPattern == "color"){
ctx.rect(0, 0, canvas.width, canvas.height);
console.log("currentcolor: " + currentcolor);
ctx.fillStyle = getColor(currentcolor);
console.log(getColor(currentcolor));
ctx.fill();
}else{
var pattern = ctx.createPattern(imgFill, 'repeat');
console.log("canvas.width: " + canvas.width);
console.log("xImgFill: " + xImgFill);
console.log(canvas.getContext);
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = pattern;
ctx.fill();
}
ctx.globalAlpha = .10;
ctx.drawImage(imgToBeFilled, 0, 0);
ctx.drawImage(imgToBeFilled, 0, 0);
ctx.drawImage(imgToBeFilled, 0, 0);
oldcolor = currentcolor;
oldxImgToBeFilled = xImgToBeFilled;
}
$(window).load(function(){
imgToBeFilled = new Image();
imgFill = new Image();
fillColorOrPattern(imgSection,currentcolor);
}
You need to add a beginPath() in there. rect() will accumulate rectangles to the path, clearRect() won't clear those. Also reset comp. mode and alpha as they are sticky.
You could avoid beginPath() if you use fillRect() instead of rect() + fill() (added example below) as fillRect() does not add to the path.
function fill(imgSection,currentcolor){
// these should really be initialized outside the loop
canvas = document.getElementById(imgSection);
ctx = canvas.getContext("2d");
// clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// clear path
ctx.beginPath();
// use default comp. mode
ctx.globalCompositeOperation = "source-over";
// reset alpha
ctx.globalAlpha = 1;
ctx.drawImage(imgToBeFilled, 0, 0);
ctx.globalCompositeOperation = "source-atop";
if (isItColorOrPattern === "color"){
// rect() accumulates on path
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = getColor(currentcolor);
ctx.fill();
// instead of rect() + fill() you could have used:
// fillRect() does not accumulate on path
// fillRect(0, 0, canvas.width, canvas.height);
}
else {
var pattern = ctx.createPattern(imgFill, 'repeat');
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = pattern;
ctx.fill();
}
ctx.globalAlpha = .1;
ctx.drawImage(imgToBeFilled, 0, 0);
ctx.drawImage(imgToBeFilled, 0, 0);
ctx.drawImage(imgToBeFilled, 0, 0);
oldcolor = currentcolor;
oldxImgToBeFilled = xImgToBeFilled;
}
Canvas workflow goes like this:
Draw some things on the canvas.
Calculate changes to the position of those things.
Clear the canvas.
Redraw all the things in their new positions.
Canvas does not "remember" where it drew your things so you cannot directly order your things to move.
But you can save the definition of your things in javascript object:
var myCircle={
centerX:50,
centerY:50,
radius:25,
fill:'blue'
}
Then you can "move" your things using the javascript objects:
myCircle.centerX += 5;
And then redraw the things at their new positions. Putting the redraw code in a function makes redrawing easier:
function redraw(){
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// redraw one or more things based on their javascript objects
ctx.beginPath();
ctx.arc( myCircle.centerX, myCircle.centerY, myCircle.radius, 0, Math.PI*2 );
ctx.closePath();
ctx.fillStyle=myCircle.fill;
ctx.fill();
}
Putting it all together:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var myCircle={
centerX:50,
centerY:50,
radius:25,
fill:'blue'
}
redraw();
document.getElementById('move').addEventListener('click',function(){
myCircle.centerX+=5;
redraw();
});
function redraw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc( myCircle.centerX, myCircle.centerY, myCircle.radius, 0, Math.PI*2 );
ctx.closePath();
ctx.fillStyle=myCircle.fill;
ctx.fill();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<button id=move>Move</button>
<br>
<canvas id="canvas" width=300 height=300></canvas>

cannot clear canvas with existing image

I am trying to blank canvas when there is image already in it.
I want to remove old image and load new image that I am getting from var getfrontimage.
But It failed me.
$('#fittocanvasfront').click(function () {
var canvas = document.getElementById("canvas-front");
var c = canvas.getContext("2d");
var getfrontimage = $('#image-tocanvaschangefront').attr('src');
var img = new resize(getfrontimage);
function resize(src) {
console.log('blank canvas');
canvas.width = canvas.width;
var image = new Image();
image.src = getfrontimage;
image.width = canvas.width;
image.height = canvas.height;
image.onload = function () {
// clearing canvas
c.clearRect(0, 0, canvas.width, canvas.height);
//loading image
c.drawImage(image, 0, 0);
//creating a hole in canvas
var centerX = canvas.width / 2;
var centerY = canvas.offsetTop;
var radius = 30;
c.beginPath();
c.arc(centerX, centerY, radius, 0, 2 * Math.PI, true);
c.fillStyle = 'black';
c.fill();
}
}
});
Into the script-
I have image in <img> tag-
var getfrontimage = $('#image-tocanvaschangefront').attr('src');
this above image is what i will be using after clearing canvas.
So I tried doing canvas empty as below when image is being loaded-
c.clearRect(0, 0, canvas.width, canvas.height);
But this didn't work, I tried doing canvas empty on click-
$('#fittocanvasfront').click(function () {
var canvas = document.getElementById("canvas-front");
var c = canvas.getContext("2d");
c.clearRect(0, 0, canvas.width, canvas.height);
});
How do I empty this canvas with existing image in it.
What you are saying is not true. You can clear of any image using clearRect. Please see fiddle with your code where image's cleared on click.
$("#canvas-front").click(function(){
c.clearRect(0, 0, canvas.width, canvas.height);
});
Hard to say what you're doing wrong, since you didn't provide the full code, use the code I provided in fiddle and all should be fine.

virtual canvas putimagedata not working

Am new to concept of virtual canvas, any idea why the below code does not work?
<script type="text/javascript">
$(document).ready(function () {
var c1 = document.createElement('canvas');
var ctx1 = c1.getContext("2d");
var c2 = document.getElementById('Canvas2');
var ctx2 = c2.getContext("2d");
c1.width = c2.width;
c1.height = c2.height;
img1 = new Image();
img1.src = 'A1.png';
img1.onload = function () {
ctx1.drawImage(this, 0, 0);
};
imgdata = ctx1.getImageData(0, 0, c2.width, c2.height);
ctx2.putImageData(imgdata, 0, 0);
});
</script>
<canvas id="Canvas2" style="display:block;position:absolute;background-color:transparent;border:1px solid red;">
Your browser does not support the HTML5 canvas tag.
</canvas>
The concept works if i draw Rectangle or any other objects but when i am loading images it
does not display the images loaded on virtual canvas. As below example works fine.
$(document).ready(function () {
var c1 = document.createElement('canvas');
var ctx1 = c1.getContext("2d");
var c2 = document.getElementById('Canvas2');
var ctx2 = c2.getContext("2d");
c1.width = c2.width;
c1.height = c2.height;
ctx1.fillRect(0, 20, 20, 20);
imgdata = ctx1.getImageData(0, 0, c2.width, c2.height);
ctx2.putImageData(imgdata, 0, 0);
});
You must also wait with getImageData etc. until the image has loaded, so move everything that needs to be done after the image has loaded inside the onload handler (or wrap them in a function called from onload):
img1.onload = function () {
ctx1.drawImage(this, 0, 0);
imgdata = ctx1.getImageData(0, 0, c2.width, c2.height);
ctx2.putImageData(imgdata, 0, 0);
};
If you don't then the image may not be loaded and drawn to canvas when you call getImageData which results in a blank byte array.

Categories