在 canvas 中附加 div 并创建无效的 DataURL

Append div in canvas and create DataURL not working

我需要显示一张图片,我需要在这张图片上方放置 2 个 div,一个 div 包含图片,另一个 div 包含文本,并且需要将所有这三者结合起来创建最终图像并将最终图像存储在 database/server 中,我正在使用 canvas 来实现这一点,而我的项目在 Ionic/AngularJS 中,我无法使用 img和文本直接没有 div,因为我还需要拖放和调整此 img 和文本的大小,如果不使用 div.

是无法实现的

这是我的 html 代码。

<div class="item item-image" ng-repeat="picture in product.images" id="mainwall">
     <img ng-src="{{wallMainImage}}" ng-init="setInitSrc(picture.src)" width="330" height="400" crossOrigin="Anonymous" id="preview1" class="wall-image"/>
     <div id="wall-design" draggable style="position: absolute;">
        <img ng-src="{{walldesign}}" />
     </div>
     <div id="wall-text" draggable>
        <p>{{wallText}}</p>
     </div>
</div>

我有 canvas 元素最后定义为

<canvas id="tempCanvas" style="position: relative;"></canvas>

在控制器中单击保存按钮时,我正在调用一个包含以下内容的函数。

var canvas = document.getElementById('tempCanvas');
var context = canvas.getContext('2d');    
var source =  document.getElementById("preview1");
var width = source.naturalWidth; 
var height = source.naturalHeight; 
canvas.width = width;
canvas.height = height;              
var canvasDiv = document.getElementById('wall-design');
canvas.appendChild(canvasDiv);
console.log("canvas", canvas)
context.drawImage(source,0,0, width, height);    
var dataURL = canvas.toDataURL("image/png");
$timeout( function(){
   $scope.wallMainImage = dataURL;
   if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
       $scope.$apply();
   }
}, 200);

我得到了一个我想要的确切 canvas 控制台,如下所示

<canvas id="tempCanvas" style="position: relative;" width="700" height="519">
   <div id="wall-design" draggable="" style="position: absolute; height: 153px; width: 54px; left: 128px; top: 105px;" class="ui-draggable ui-draggable-handle ui-resizable">
        <img ng-src="images/designs/3.jpg" src="images/designs/3.jpg">
        <div class="ui-resizable-handle ui-resizable-e" style="z-index: 90;"></div>
        <div class="ui-resizable-handle ui-resizable-s" style="z-index: 90;"></div>
        <div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90;"></div>
   </div></canvas>

而且我还得到一个 datURL,它在编码字母中很长,最后我得到一个只有起始图像的图像,而其他需要在该图像上方显示的图像未显示

请告诉我..我哪里做错了

提前致谢..

在这里我给出了解决方案,它适用于我的情况

html2canvas(angular.element('#wallimageid'), {
      onrendered: function(canvas) {
         var img = canvas.toDataURL("image/png")
         console.log("img", img);
         $scope.savedGalleryImage = img;
      }, 
      useCORS:true
})

我正在使用 angularjs 指令,如果有人想使用 jquery 执行此操作,只需将 angular.element 替换为 $

我使用 useCORS 来使用我们本地存储中不可用的图像 src,而不是来自某些站点。

用户还需要下载 html2canvas,我已经通过 git 使用此命令克隆

下载了这个
git clone --recursive git://github.com/niklasvh/html2canvas.git

并通过

在html文件中指定
<script src="js/lib/html2canvas/dist/html2canvas.js"></script>

这里使用你自己的路径

谢谢