gpt4 book ai didi

javascript - 如何在fabric.js中根据下 Canvas 调整上 Canvas 的大小?

转载 作者:行者123 更新时间:2023-12-03 03:23:53 26 4
gpt4 key购买 nike

我正在织物 Canvas 上添加裁剪后的图像和 Logo ,裁剪后的图像和 Logo 位于下部和上部 Canvas 上。现在的问题是如何设置织物 Canvas 的最大宽度,以便我可以将 Logo 拖出 Canvas 。

我已经对现有 Canvas 、 Logo 和裁剪图像实现了最大宽度。这里的问题是我无法将 Logo 拖动到整个 Canvas 。

这是代码

<div class="container"> 

<div style="position: relative;" id="editor">
<canvas id="canvas" class="img-responsive"></canvas>
</div>

<div class="container">
<a class="btn btn-primary" id="save">Save</a>
<a class="btn btn-primary" id="download">Download</a>

<script>
$(function () {
var source = sessionStorage.getItem("source");
$("#background").attr("src", source);
});
setTimeout(function () {
var myImg = document.querySelector("#background");
var realWidth = myImg.naturalWidth;
var realHeight = myImg.naturalHeight;
$("canvas").attr("width", realWidth);
$("canvas").attr("height", realHeight);
var source = document.getElementById('background').src;
var canvas = new fabric.Canvas('canvas');
canvas.width=realWidth;
canvas.height=realHeight;
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'images/logo.png';
var imgInstance = new fabric.Image(img, {
width: 200
, height: 45
});
canvas.add(imgInstance);
canvas.setBackgroundImage(source, canvas.renderAll.bind(canvas), {
backgroundImageOpacity: 0.5
, backgroundImageStretch: false
});


}, 2000);
$("#save").click(function(){
function blobCallback(iconName) {
return function (b) {
var a = document.getElementById('download');
a.download = iconName + ".jpg";
a.href = window.URL.createObjectURL(b);
}
}
canvas.toBlob(blobCallback('wallpaper'), 'image/vnd.microsoft.jpg', '-moz-parse-options:format=bmp;bpp=32');
});

最佳答案

作为一个fabricjs Canvas ,不要直接操作宽度和高度,而是使用正确的方法:

setTimeout(function () {
var myImg = document.querySelector("#background");
var realWidth = myImg.naturalWidth;
var realHeight = myImg.naturalHeight;
var source = document.getElementById('background').src;
var canvas = new fabric.Canvas('canvas');
canvas.setDimensions({ width: realWidth, height: realHeight });
var img = new Image();
// use a load callback to add image to canvas.
img.src = 'images/logo.png';
var imgInstance = new fabric.Image(img, {
width: 200
, height: 45
});
canvas.add(imgInstance);
canvas.setBackgroundImage(source, canvas.renderAll.bind(canvas), {
backgroundImageOpacity: 0.5
, backgroundImageStretch: false
});


}, 2000);

关于javascript - 如何在fabric.js中根据下 Canvas 调整上 Canvas 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38767640/

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