canvas自动适应画布,canvas元素也自动适应画布的大小

作为专业的前端技术人员,到那时技术还凑合,不够硬,但是我会给大家介绍一下我所学到,并认为有用的东西。

canvas

在这我要给大家介绍一下canvas,这个应该是属于h5的新知识,大家没事的是偶都可以试一试,很简单那的,也很适合初学者,这里我要给大家普及的就是canvas自动适应画布。

下面首先要创建画布,贴代码:

canvas自动适应画布,canvas元素也自动适应画布的大小

然后是首先要自动适应画布:

canvas自动适应画布,canvas元素也自动适应画布的大小

最后一步是canvas画出的元素自动适应,这个尤其的重要,我研究了一天

canvas自动适应画布,canvas元素也自动适应画布的大小

下面贴所有源代码;如有不对的地方请沟通。

body {

margin: 0;

overflow: hidden;

}

#div {

width: 100%;

height: 500px;

/*background: black;*/

z-index: 0;

background: pink;

}

canvas {

border: 1px solid red;

display: block;

z-index: -1;

}

//首先要创建画布

var canvas = document.getElementById('canvas');

var ctx = canvas.getContext('2d');

$(document).ready(function() {

resize();

ss()

});

//自适应canvas的大小以及长宽高

// set this to false to maintain the canvas aspect ratio, or true otherwise

//将此设置为false以维护画布长宽比,否则设置为true

var stretch_to_fit = false;

function resize() {

//得到canvas的宽和高的比例

var divW = $("#div").width();

var divh = $("#div").height();

// aspect ratio

var widthToHeight = Math.round(canvas.width / canvas.height)

//console.log(widthToHeight)

//console.log(widthToHeight)

var newWidthToHeight = widthToHeight;

var newWidth = divW - 2,

newHeight = divh - 2;

if(stretch_to_fit) {

//widthToHeight = divW / divh

} else {

newWidthToHeight = newWidth / newHeight;

}

if(newWidthToHeight > widthToHeight) {

newWidth = newHeight * widthToHeight;

canvas.height = newHeight;

canvas.width = newWidth;

} else {

newHeight = newWidth / widthToHeight;

canvas.width = newWidth;

canvas.height = newHeight;

}

};

window.addEventListener('resize', function() {

resize();

ss()

}, false);

window.addEventListener('orientationchange', function() {

resize();

ss()

}, false);

//漏斗

//canvas的默认是996 高是498 以这个作为标准

function loudou(x, y, w, h) {

if(w > 1) {

console.log("放大");

ctx.beginPath();

ctx.moveTo(x, y);

ctx.lineTo(x + 10 / w, y);

ctx.lineTo(x, y + 20 / h);

ctx.lineTo(x + 10 / w, y + 20 / h);

ctx.lineWidth = '1'

ctx.strokeStyle = '#FFFFFF';

ctx.closePath();

ctx.fill();

ctx.stroke();

} else {

console.log("缩小");

ctx.beginPath();

ctx.moveTo(x, y);

ctx.lineTo(x + 10 * w, y);

ctx.lineTo(x, y + 20 * h);

ctx.lineTo(x + 10 * w, y + 20 * h);

ctx.lineWidth = '1'

ctx.strokeStyle = '#FFFFFF';

ctx.closePath();

ctx.fill();

ctx.stroke();

}

}

//初始化加载这个函数

function ss() {

var canshu_width = canvas.width / 996;

var canshu_height = canvas.height / 498

ctx.beginPath();

loudou(100 * canshu_width, 100 * canshu_height, canshu_width, canshu_height);

}


分享到:


相關文章: