user3928256 user3928256 - 5 months ago 26
jQuery Question

Using jQuery with Canvas not working?

I'm trying to put a picture in the center of a canvas using jQuery. First I did it without jQuery:

function initCanvas() {
var canvas = document.getElementById("canvas");
canvas.height = CANVAS_HEIGHT;
canvas.width = CANVAS_WIDTH;
canvas.style.backgroundColor = CANVAS_COLOR; // black color
return canvas;
}

function drawEarth(ctx) {
var img = new Image();
img.src = EARTH_PNG;
img.addEventListener("load", function () {
ctx.drawImage(img, CANVAS_X - EARTH_X, CANVAS_Y - EARTH_Y, EARTH_WIDTH, EARTH_HEIGHT);
});
}

function render() {
var canvas = initCanvas();
var ctx = canvas.getContext("2d");
drawEarth(ctx);
}

// init function
(function () {
render();
})();


and it worked. Then I modified the
initCanvas()
function:

function initCanvas(){
var canvas = $("#canvas");
canvas.height(CANVAS_HEIGHT);
canvas.width(CANVAS_WIDTH);
canvas.css({"background-color": CANVAS_COLOR}); // black color
return canvas[0];
}


it did not draw the picture. The background was black though. I check the document it says For example,
$( "#mydiv" ).css( "color", "green" )
is equivalent to
document.getElementById( "mydiv" ).style.color = "green"
.
So I don't know what's wrong here. Anyone can help? Thanks!

Thanks to comment below I changed the init code after using jQuery:

$(function (){
render();
});


but it's still not working.

Answer

You can't do canvas width/height by .css() .But context.canvas.width/height is working with jquery .You should change a little initCanvas and render function.

function render() {
    var canvas = initCanvas();    
    drawEarth(canvas);
}

function initCanvas() {
    var c = $("#canvas");
    var ctx = c[0].getContext("2d");
    ctx.canvas.height = CANVAS_HEIGHT;
    ctx.canvas.width = CANVAS_WIDTH;
    c.css({"background-color": CANVAS_COLOR}); // black color
    return ctx;
}
Comments