gpt4 book ai didi

javascript - 动态获取 Canvas 图像的宽度和高度,并在一页上使用 JavaScript 创建另一个 Canvas

转载 作者:行者123 更新时间:2023-12-02 22:10:28 36 4
gpt4 key购买 nike

我正在使用带有动态图像的 JavaScript 创建 Canvas 。现在我想根据图像动态获取 Canvas 的高度和宽度。并在同一页面上创建另一个 Canvas 。我在这里附上我的代码。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
var _puzzleWidth = 640;
var _puzzleHeight = 480;
var _stage;
function init(){

var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
//canvas.width = _puzzleWidth;
//canvas.height = _puzzleHeight;
_stage = canvas.getContext('2d');
canvas.style.border = "1px solid";
//draw();
var img = new Image();
img.onload = function(){
_stage.drawImage(img, 0, 0);
}
img.src = "http://lorempixel.com/output/animals-q-g-640-480-3.jpg";

var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
}

</script>
</head>
<body onload="init();"></body>
</html>

提前致谢。

最佳答案

尝试下面的代码:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var _puzzleWidth = 640;
var _puzzleHeight = 480;
var _stage;
var _stage2;
function init(){

var canvas2 = document.createElement('canvas');
canvas2.id = "CursorLayer2";

var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";

_stage = canvas.getContext('2d');
canvas.style.border = "1px solid";

_stage2 = canvas2.getContext('2d');
canvas2.style.border = "1px solid";

var img = new Image();
var img1=new Image();

img.onload = function(){
canvas.width = this.width;
canvas.height = this.height;
_stage.drawImage(img, 0, 0);
}

img1.onload = function(){
canvas2.width = this.width;
canvas2.height = this.height;
_stage2.drawImage(img1,0,0);

}

img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTfSV9AGQi9c48oRysYiuSs9Bs4J3B2p4R3eh-z1hsS-Z01HD17";
img1.src = "http://lorempixel.com/output/animals-q-g-640-480-3.jpg";

var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);

var body1 = document.getElementsByTagName("body")[0];
body1.appendChild(canvas2);
}
</script>
</head>
<body onload="init();"></body>
</html>

关于javascript - 动态获取 Canvas 图像的宽度和高度,并在一页上使用 JavaScript 创建另一个 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59574013/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com