我在画布上画一个图像。
问题
完成后,我想点击一个按钮将画布更改为另一个容器div
,在这种情况下没有任何反应..
单击新画布时会出现在新容器上,但未附加图像....
我做错了什么? http://jsfiddle.net/7vZnH/1691/
$("button").prop("disabled",true);
$(document).on("click",".imageToMeme",function(){
$("button").prop("disabled",false);
newStart_Scr = $(this).attr("src");
//alert(newStart_Scr);
$("#start-image").attr("src",newStart_Scr);
drawMeme();
});
$("button").on("click",function(){
$("#newContainer").html("<canvas id='meme' ></canvas>");
$(".memeContainer").empty();
drawMeme();
});
var canvas = document.getElementById('meme');
ctx = canvas.getContext('2d');
// core drawing function
var drawMeme = function() {
var img = document.getElementById('start-image');
var imgWidth = img.clientWidth;
var imgHeight = img.clientHeight;
var memeWidth = 440;
var imgRatio = memeWidth/imgWidth;
// initialize canvas element with desired dimensions
canvas.width = memeWidth;
canvas.height = parseInt(imgHeight*imgRatio);// alert(canvas.height)
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'red';
ctx.fillRect(0,0,canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, imgWidth, imgHeight, 0, 0, canvas.width, canvas.height);
}
.meme{opacity:0;}
.imageToMeme{height:90px;display:inline-block;}
#newContainer{height:100px;width:100px;border:1px solid red;display:inline-block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Click to add to canvas <br>
<img src="https://picsum.photos/200
" class="imageToMeme" />
<button>
Change canvas of container
</button>
<div id="newContainer"></div>
<hr>
<div class="memeContainer">
<canvas id="meme" style="" ></canvas>
</div>
<hr>
<img src="https://picsum.photos/200/300
" id="start-image" class="meme" />
答案 0 :(得分:1)
您需要使用append()函数将元素移动到新容器,而不是添加具有相同ID的画布。您不需要清空旧容器,因为追加将移动该项目。此外,如果您希望画布具有与容器相同的高度和宽度,则需要手动设置它们
$("#meme").height($("#newContainer").height());
$("#meme").width($("#newContainer").width());
$("#newContainer").append($("#meme"));
你可以在这里找到完整的小提琴http://jsfiddle.net/7vZnH/1699/