簡體   English   中英

從 javascript 函數創建 HTML5 畫布

[英]Create HTML5 canvas from javascript function

這是我的 html

<p>
   <canvas id="canvas" width="340" height="460" style="border:1px solid #BBBBBB;"></canvas>
</p>

我的js

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var image = new Image();
image.src = 'abc.jpg';

現在我想從新的javascript函數在相同的位置創建新的畫布,比如

function newCanvas () {
    can.width = X;
    can.height = Y;

    var newCanvas = document.getElementById('canvas');
    var img = new Image();
    img.src = 'xyz.jpg';    
    var ctx = newCanvas.getContext('2d');
}

在按鈕上單擊新畫布應在相同位置創建。

有什么辦法嗎?

在這里您可以看到兩個畫布相互重疊。 點擊第二個后第一次應該消失。 但兩者都是可見的。

<script type="text/javascript">
function canvasA(){
var canvas = document.createElement('canvas');

canvas.id = "CursorLayer";
canvas.width = 340;
canvas.height = 460;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";


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

cursorLayer = document.getElementById("CursorLayer");

console.log(cursorLayer);

var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(255, 0, 0, 0.2)";
ctx.fillRect(100, 100, 200, 200);
ctx.fillStyle = "rgba(0, 255, 0, 0.2)";
ctx.fillRect(150, 150, 200, 200);
ctx.fillStyle = "rgba(0, 0, 255, 0.2)";
ctx.fillRect(200, 50, 200, 200);
document.body.appendChild(canvas);
};

function character(){
var canvas = document.createElement('canvas');

canvas.id = "CursorLayer";
canvas.width = 340;
canvas.height = 460;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";


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

cursorLayer = document.getElementById("CursorLayer");

console.log(cursorLayer);

var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(255, 0, 0, 0.2)";
ctx.fillRect(100, 100, 200, 200);
ctx.fillStyle = "rgba(0, 255, 0, 0.2)";
ctx.fillRect(150, 150, 200, 200);
ctx.fillStyle = "rgba(0, 0, 255, 0.2)";
ctx.fillRect(200, 50, 200, 200);
document.body.appendChild(canvas);
 };

</script>
<button onclick="canvasA();">Hello</button>
<button onclick="character();">Hello</button>
</body>

你需要在onload事件中使用.drawImage()

 function newCanvas() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = document.getElementById('inputImg').value; img.onload = function() { canvas.width = this.width; canvas.height = this.height; ctx.drawImage(img, 0, 0); } }
 <input style="width: 300px" type="text" id="inputImg" placeholder="image url" value="https://lorempixel.com/output/nature-qc-300-300-3.jpg"> <input type="button" onclick="newCanvas()" value="set image"> <p><canvas id="canvas" width="300" height="300" style="border:1px solid #BBBBBB;"></canvas></p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM