Image not appearing in canvas - html

I'm trying to load an image on my HTML5 canvas. I'm following a tutorial and I've done everything precisely.
My console prints "image loaded", so I know that it has found the png file. However, nothing shows up on screen.
I have tried resizing the canvas, and trying to make the image appear on different coordinates, to no avail.
<body>
<canvas id="my_canvas"></canvas>
</body>
<script>
var canvas = null;
var context = null;
var basicImage = null;
var setup = function() {
// Set up canvas
canvas = document.getElementById("my_canvas");
context = canvas.getContext('2d'); // lets us modify canvas visuals later
canvas.width = window.innerWidth; // 1200
canvas.height = window.innerHeight; // 720
// Load an image
basicImage = new Image();
basicImage.src = "bb8.png";
basicImage.onload = onImageLoad();
}
var onImageLoad = function() {
console.log("image loaded");
context.drawImage(basicImage, 0, 0);
}
setup();
</script>

Rather than drawing the image on basicImage.onload, try it on window.onload
var setup = function() {
// Set up canvas
canvas = document.getElementById("my_canvas");
context = canvas.getContext('2d'); // lets us modify canvas visuals later
canvas.width = window.innerWidth; // 1200
canvas.height = window.innerHeight; // 720
// Load an image
basicImage = new Image();
basicImage.src = "bb8.png";
}
window.onload = function() {
console.log("image loaded");
context.drawImage(basicImage, 0, 0);
}
setup();

Related

Reveal background image on mouse move over front image

I want to reveal the background image on mouse move on the front image. I have tried it using fabricjs but it seems the pattern image offset is updated on mouse up.
I have also tried it using the making the pixels transparent of image on mouse move but there are performance issue on slow devices. Can you suggest any better solution.
HTML
<canvas id="container"></canvas>
JS
var canvasWidth = window.innerWidth;
var canvasHeight = window.innerHeight;
var backgroundUrl = "http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image2.jpg";
var frontUrl = "http://tofurious.wpengine.netdna-cdn.com/images/textures/texture-8.jpg";
var canvas = new fabric.Canvas('container', {
width:canvasWidth,
height:canvasHeight,
isDrawingMode: true
});
fnDrawImage(backgroundUrl);
drawPattern()
function fnDrawImage(_url){
var Image = fabric.Image.fromURL(_url, function(oImg) {
oImg.width = canvasWidth;
oImg.height = canvasHeight;
oImg.selectable = false;
canvas.add(oImg);
});
}
function drawPattern(){
var img = new Image();
img.src = frontUrl;
img.onload = function(){
img.width = canvasWidth;
img.height = canvasHeight;
fnTexturePattern(img);
//fnStartFreeDrawing(img);
}
}
function fnTexturePattern(_img){
var texturePatternBrush = new fabric.PatternBrush(canvas);
texturePatternBrush.source = _img;
canvas.freeDrawingBrush = texturePatternBrush;
canvas.freeDrawingBrush.width = 30;
}
JSFiddle - http://jsfiddle.net/3qp5y9jb/

Play video on canvas and preserve the last frame/image on canvas

I'm using the following script code to draw a video on canvas:
$("#vPlayer").on('play', function (e) {
var canvas = $('canvas')[0];
var ctx = canvas.getContext('2d');
var $this = this;
canvas.width = 640;
canvas.height = 480;
(function loop() {
if (!$this.paused && !$this.ended) {
ctx.drawImage($this, 0, 0, 640, 480);
setTimeout(loop, 1000 / 30); // drawing at 30fps
}
})();
});
The code works well, but in my case, I want to change the video source (src attribute) of the video tag every 2 mins. When I set the src attr for the video and during the loading time for the video, the canvas displays white screen. How can I preserve the last image of video and do not clear the canvas?
It is a little bit weird because, when I don't set the width and height for the canvas, the last frame is preserved, but I need to set the size.
Every time you set the size of the canvas it will be cleared.
To avoid this you need to set the size at the "beginning", before you start drawing to it. In this case I would recommend you set it outside your event handler as well as the initializing of the canvas and context variable:
var canvas = $('canvas')[0];
var ctx = canvas.getContext('2d');
canvas.width = 640;
canvas.height = 480;
$("#vPlayer").on('play', function (e) {
var $this = this;
(function loop() {
if (!$this.paused && !$this.ended) {
ctx.drawImage($this, 0, 0, 640, 480);
setTimeout(loop, 1000 / 30); // drawing at 30fps
}
})();
});

How can I use a dynamically-resized hitArea for an EaselJS DisplayObject?

I'd like to use a hitArea to capture click events in my EaselJS project, but the hitArea Shape I've assigned doesn't seem to be respected.
jsFiddle Example
var stage = new createjs.Stage($("#game")[0]);
// This will be a big button
var container = new createjs.Container();
stage.addChild(container);
// This defines the hit area of the button
var hitArea = new createjs.Shape();
var hitAreaGraphics = hitArea.graphics;
// A 1x1 black square, centered about the origin
hitAreaGraphics.beginFill("#000").drawRect(-0.5, -0.5, 1, 1).endFill();
// Assign the hitArea
container.hitArea = hitArea;
// container.addChild(hitArea);
container.onTick = function() {
var canvas = container.getStage().canvas;
container.x = canvas.width / 2;
container.y = canvas.height / 2;
container.scaleX = canvas.width;
container.scaleY = canvas.height;
};
container.onPress = function() {
alert("Eureka!");
};
// Run the simulation
updater = {
tick: function() { stage.update(); }
};
createjs.Ticker.addListener(updater);
​
If I add the hitArea shape as a child of the container object, the click events work fine.

Rotating full window canvas

I am doing simple (for now) application to draw on canvas.
I can draw simple shapes like putting dots, squares, lines, but when I try to rotate whole image - nothing happens. No errors, no rotation. Please advise where is problem.
Canvas is updated to window size by function onwindowresize:
function adaptSize() {
var canvas = document.getElementById('canvas');
// set size to window
canvas.setAttribute('width',window.innerWidth);
canvas.setAttribute('height',window.innerHeight);
var ctx = canvas.getContext("2d");
// set state size to window
ctx.width = window.innerWidth;
ctx.height = window.innerHeight;
drawSaved();
inform('Canvas re-drawed - window resized');
}
Each draw function saves itself inlocalstorage to re-draw, for example placing dot:
function placeDot(x,y){
if(document.getElementById('colors').hasAttribute('chosen')){ var color = document.getElementById('colors').getAttribute('chosen');}else{ var color = 'rgba(0,0,0,1)'; }
var canvas = document.getElementById("canvas");
if(canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.save();
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x-2,y-2,5,0,Math.PI*2,true);
ctx.fill();
ctx.restore();
}
save("//Dot("+x+","+y+",5,'"+color+"')");
return false;
}
than re-draw function:
function drawSaved(){
var picture = localStorage.getItem("picture");
var drawstate =document.getElementById('drawstate');
console.log('picture:'+picture+'.');
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
if((picture=="")||(picture==null)){
picture = ""
localStorage.setItem("picture", picture);
drawstate.innerHTML='picture empty';
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
console.log('cleared');
}else{
console.log(picture);
saved = picture.split('//');
for(var i=1;i<saved.length;i++){
eval(saved[i]);
}
drawstate.innerHTML='picture restored';
}
}
So, creating rotation:
function turn(angle){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
console.log('saved');
ctx.rotate(angle);
console.log('rotated by'+angle);
ctx.restore();
console.log('restored');
save("//Turn('"+angle+"')");
return false;
}
All this gives no effect on rotation - or any other transformation. Drawing is OK.
Please help.
Thanks
Pifon
PS: this programme is: http://www.pifon.com/3d/ rotation should work on arrow right press.
Full script: http://www.pifon.com/3d/js/index.js
You have two functions named Turn(angle) in your original source.
Apparently it starts to work.
Corrected turn function.
function turn(angle){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(angle*(Math.PI/180));
ctx.translate(-canvas.width/2,-canvas.height/2);
inform('turn executed (by: '+angle+' degrees)');
drawSaved();
return false;
}
Thanks for your help.
Pifon

Canvas elements appear skewed in Webkit with context blender

EDIT: Below is the original post, but I have figured out the problem. It appears the problem was with using a decimal number as the Y coordinate (destY). I sorted this out by rounding:
var rand = {
destX: Math.round(Math.random()*main.canvas.width),
destY: Math.random()*main.canvas.height
}
I have included images to show the difference between Firefox and Chrome. As you can see the images I have blended onto the canvas are skewed. Has anyone experienced this before? Is it a problem with context blender, or Webkits canvas in general?
var main;
$(document).ready(function(){
var canvas = document.getElementById('canvas');
main = canvas.getContext('2d');
main.canvas.width = $(window).width();
main.canvas.height = $(window).height()/2;
});
$(window).load(function(){
var array = new Array();
$('img').each(function(){
var temp = document.createElement('canvas');
var ctx = temp.getContext('2d');
ctx.canvas.width = this.width;
ctx.canvas.height = this.height;
ctx.drawImage(this,0,0);
var rand = {
destX: Math.random()*main.canvas.width,
destY: Math.random()*main.canvas.height
}
ctx.blendOnto(main,'multiply',rand);
});
});