简体   繁体   中英

Canvas height and width

When programming in HTML canvas, the js dimensions of the canvas don't always match the css dimensions. Why is this happening and how can I fix this?

I've found the problem. I was setting the dimensions of the using CSS, when you actually have to set the width and height attributes. This was causing it to be stretched/skewed.

var canvas = $('<canvas/>').attr({width: cw, height: ch}).appendTo('body');

http://jsfiddle.net/h2yJn/66/

You can try to set the width and height of the canvas to be equal to the dimensions of the window object:

function createCanvas() {
    var ctx = //the canvas context;
    ctx.canvas.width  = window.innerWidth;
    ctx.canvas.height = window.innerHeight;
   //your code
}

In addition, it is a good idea to set the body and html tags to the full width of the window:

body, html{
     height: 100%;
     width:  100%;
}

You can also do this by using pure javascript and set the dimensions of the canvas in javascript depending on your CSS values:

//Get Canvas
var canvas = document.getElementById("canv");

// Get computed style of the canvas element.
var cstyle = window.getComputedStyle(canvas);

// Returns the width as str in px: e.g. 600px.
// Parse resolves that issue.
canv.width = parseInt(cstyle.width);
canv.height = parseInt(cstyle.height);

Demo: https://jsfiddle.net/ofaghxfq/2/

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