简体   繁体   中英

I cannot resize the Canvas in JavaScript

Ok, so, I'm working on a project in HTML5 and JavaScript. I'm trying to resize a Canvas, but it won't work. I don't think it's my browser, though, because I am using the latest version of FireFox. I've also researched this issue for a while, and I am confident I'm doing this correctly. So, I don't know why it won't work. Here's my Code:

var level = 1;
var levelImg = undefined;
var width = 0;
var height = 0;

var cnvs = document.getElementById("cnvs").getContext("2d");

width = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;

height = window.innerHeight
    || document.documentElement.cleintHeight
    || document.body.cleintHeight;

cnvs.width = width;
cnvs.height = height;

window.onload = function Init(){

    levelImg = document.getElementById("level" + level);

    setInterval("Draw()", 3);

}

function Draw(){

    //Clear the Screen
    cnvs.clearRect(0, 0, width, height);

    //Draw stuff
    DrawLevel();

}

function DrawLevel(){
    cnvs.fillRect(0, 0, 10, 10);
}

Any help is appreciated. Thanks.

First correct all the typos in you code. Use the browser console to detect errors.

Difference between canvas and the context

var cnvs = document.getElementById("cnvs").getContext("2d");

cnvs variable is not a canvas but the context for the canvas. Canvas is the element and context is the object used to write in the canvas. To access the canvas you need to do this:

var canvas = document.getElementById("cnvs");
var cnvs = canvas.getContext('2d'); //context

Now when you are trying to change the canvas with, you use canvas, not cnvs .

canvas.width = width;
canvas.height = height;

SetInterval expects a function and a number value that represents milliseconds. "Draw()" is a string, not a function, and 3 is a really small number between each time the browser draws on canvas. It works, but it's very inefficient.

Other point about setInterval. Avoid it by using requestAnimationFrame() instead. Take a look here: setTimeout or setInterval or requestAnimationFrame

Defining var levelImg = undefined has no utility. It can be replaced by var levelImg;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM