如何设置画布图像的宽度和高度

时间:2017-07-10 10:02:01

标签: jquery angularjs html5-canvas

我使用角度画布画家,我想将图像高度设置为自动,宽度设置为画布图像的100%,但它只取像素值。

 options.width = options.width || '480';
   options.height = options.height || '350';

任何人都可以帮我解决这个问题。

以下是Js小提琴[https://jsfiddle.net/Raviteja123/vjy2w0e3/1/]

1 个答案:

答案 0 :(得分:0)

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>


<div ng-app="myApp" ng-controller="myctrl as canvasctrl">
<input type="file" name="img[]" class="file" onchange="angular.element(this).scope().ocular_file(this.files)" ngf-select ng-model="file" style="position:relative;width:auto;height:auto;">
<div pw-canvas            versionright="canvasctrl.versionright"  options="{undo: true,color: selectedColor, lineWidth: selectedLineWidth,imageSrc:thumbnail.dataUrl}"ng-show="showCanvasdiv" >
 <div class="pwCanvasPaint" style=""></div>
  </div>
  <div pw-color-selector="['#000', '#9CB199', '#CF3759', '#485247', '#E77547', '#D38E47', '#0A6A74', '#153974']" color="selectedColor">
      </div>
      
                      
<div class="undo">
   <button ng-click="canvasctrl.undo()"
   ng-disabled="canvasctrl.versionright < 1">Undo ({{canvasctrl.versionright}})</button></div>
  
                                      
</div>
</body>
<style>
.alpha{height:100%;width:100%;border:1px solid red;}
canvas{height:100%;width:100%;border:1px solid green;}

</style>
<script>
var app = angular.module("myApp", []);
app.directive('pwCanvas', function() {
    return {
      restrict: 'AE',
      scope: {
        options: '=',
        versionright: '='
      },
      //templateUrl: '../templates/canvas.html',
      link: function postLink(scope, elm) {

        var isTouch = !!('ontouchstart' in window);
        elm.addClass('alpha');
        var PAINT_START = isTouch ? 'touchstart' : 'mousedown';
        var PAINT_MOVE = isTouch ? 'touchmove' : 'mousemove';
        var PAINT_END = isTouch ? 'touchend' : 'mouseup';

        //set default options
        var options = scope.options;
        options.canvasId = options.customCanvasId || 'pwCanvasMain';
        options.tmpCanvasId = options.customCanvasId ? (options.canvasId + 'Tmp') : 'pwCanvasTmp';
       options.backgroundColor = options.backgroundColor || '#fff';
        options.color = options.color || '#000';
        options.undoEnabled = options.undoEnabled || false;
        options.opacity = options.opacity || 0.9;
        options.lineWidth = options.lineWidth || 1;
        options.undo = options.undo || false;
        //alert(options.imageSrc);
        options.imageSrc = options.imageSrc || 'img/optha/image-workgd.png';
       
        // background image
        if (options.imageSrc) {

          var image = new Image();
          image.onload = function() {
            ctx.drawImage(this, 0, 0);
          };
          image.src = options.imageSrc;
          scope.$watch(function(){
          	return options.imageSrc;
          },function(newVal){
          	scope.options.imageSrc = newVal;
          });
           scope.$watch('options.imageSrc', function(newVal) {
           //	alert(newVal);
           		scope.options.imageSrc =  newVal;
           		image.src = newVal;
           });

        }

        //undo
        if (options.undo) {
          var undoCache = [];
          scope.$watch(function() {
            return undoCache.length;
          }, function(newVal) {
            scope.versionright = newVal;
          });

          scope.$watch('versionright', function(newVal) {
            if (newVal < 0) {
              scope.versionright = 0;
              return;
            }
            if (newVal >= undoCache.length) {
              scope.versionright = undoCache.length;
              return;
            }
            undo(newVal);
          });
        }

        //create canvas and context
        var canvas = document.createElement('canvas');
        canvas.id = options.canvasId;
        var canvasTmp = document.createElement('canvas');
        canvasTmp.id = options.tmpCanvasId;
        angular.element(canvasTmp).css({
          position: 'absolute',
          top: 0,
          left: 0
        });
        elm.find('div').append(canvas);
        elm.find('div').append(canvasTmp);
        var ctx = canvas.getContext('2d');
        var ctxTmp = canvasTmp.getContext('2d');

        //inti variables
        var point = {
          x: 0,
          y: 0
        };
        var ppts = [];

        //set canvas size
        canvas.width = canvasTmp.width;
        canvas.height = canvasTmp.height;

        //set context style
        ctx.fillStyle = options.backgroundColor;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctxTmp.globalAlpha = options.opacity;
        ctxTmp.lineJoin = ctxTmp.lineCap = 'round';
        ctxTmp.lineWidth = 10;
        ctxTmp.strokeStyle = options.color;


        //Watch options
        
        scope.$watch('options.lineWidth', function(newValue) {
          if (typeof newValue === 'string') {
            newValue = parseInt(newValue, 10);
          }
          if (newValue && typeof newValue === 'number') {
            ctxTmp.lineWidth = options.lineWidth = newValue;
          }
        });

        scope.$watch('options.color', function(newValue) {
          if (newValue) {
            //ctx.fillStyle = newValue;
            ctxTmp.strokeStyle = ctxTmp.fillStyle = newValue;
          }
        });

        scope.$watch('options.opacity', function(newValue) {
          if (newValue) {
            ctxTmp.globalAlpha = newValue;
          }
        });

        var getOffset = function(elem) {
          var bbox = elem.getBoundingClientRect();
          return {
            left: bbox.left,
            top: bbox.top
          };
        };

        var setPointFromEvent = function(point, e) {
          if (isTouch) {
            point.x = e.changedTouches[0].pageX - getOffset(e.target).left;
            point.y = e.changedTouches[0].pageY - getOffset(e.target).top;
          } else {
            point.x = e.offsetX !== undefined ? e.offsetX : e.layerX;
            point.y = e.offsetY !== undefined ? e.offsetY : e.layerY;
          }
        };


        var paint = function(e) {
          if (e) {
            e.preventDefault();
            setPointFromEvent(point, e);
          }

          // Saving all the points in an array
          ppts.push({
            x: point.x,
            y: point.y
          });

          if (ppts.length === 3) {
            var b = ppts[0];
            ctxTmp.beginPath();
            ctxTmp.arc(b.x, b.y, ctxTmp.lineWidth / 2, 0, Math.PI * 2, !0);
            ctxTmp.fill();
            ctxTmp.closePath();
            return;
          }

          // Tmp canvas is always cleared up before drawing.
          ctxTmp.clearRect(0, 0, canvasTmp.width, canvasTmp.height);

          ctxTmp.beginPath();
          ctxTmp.moveTo(ppts[0].x, ppts[0].y);

          for (var i = 1; i < ppts.length - 2; i++) {
            var c = (ppts[i].x + ppts[i + 1].x) / 2;
            var d = (ppts[i].y + ppts[i + 1].y) / 2;
            ctxTmp.quadraticCurveTo(ppts[i].x, ppts[i].y, c, d);
          }

          // For the last 2 points
          ctxTmp.quadraticCurveTo(
            ppts[i].x,
            ppts[i].y,
            ppts[i + 1].x,
            ppts[i + 1].y
          );
          ctxTmp.stroke();
        };

        var copyTmpImage = function() {
          if (options.undo) {
            scope.$apply(function() {
              undoCache.push(ctx.getImageData(0, 0, canvasTmp.width, canvasTmp.height));
              if (angular.isNumber(options.undo) && options.undo > 0) {
                undoCache = undoCache.slice(-1 * options.undo);
              }
            });
          }
          canvasTmp.removeEventListener(PAINT_MOVE, paint, false);
          ctx.drawImage(canvasTmp, 0, 0);
          ctxTmp.clearRect(0, 0, canvasTmp.width, canvasTmp.height);
          ppts = [];
        };

        var startTmpImage = function(e) {
          e.preventDefault();
          canvasTmp.addEventListener(PAINT_MOVE, paint, false);

          setPointFromEvent(point, e);
          ppts.push({
            x: point.x,
            y: point.y
          });
          ppts.push({
            x: point.x,
            y: point.y
          });

          paint();
        };

        var initListeners = function() {
          canvasTmp.addEventListener(PAINT_START, startTmpImage, false);
          canvasTmp.addEventListener(PAINT_END, copyTmpImage, false);

          if (!isTouch) {
            var MOUSE_DOWN;

            document.body.addEventListener('mousedown', mousedown);
            document.body.addEventListener('mouseup', mouseup);

            scope.$on('$destroy', removeEventListeners);

            canvasTmp.addEventListener('mouseenter', mouseenter);
            canvasTmp.addEventListener('mouseleave', mouseleave);
          }

          function mousedown() {
            MOUSE_DOWN = true;
          }

          function mouseup() {
            MOUSE_DOWN = false;
          }

          function removeEventListeners() {
            document.body.removeEventListener('mousedown', mousedown);
            document.body.removeEventListener('mouseup', mouseup);
          }

          function mouseenter(e) {
            // If the mouse is down when it enters the canvas, start a path
            if (MOUSE_DOWN) {
              startTmpImage(e);
            }
          }

          function mouseleave(e) {
            // If the mouse is down when it leaves the canvas, end the path
            if (MOUSE_DOWN) {
              copyTmpImage(e);
            }
          }
        };

        var undo = function(versionright) {
        	console.log(undoCache.length);
          if (undoCache.length > 0) {
            ctx.putImageData(undoCache[versionright], 0, 0);
            undoCache = undoCache.slice(0, versionright);
          }
        };

        initListeners();
      }
    };
  });

app.controller("myctrl", function($scope,$timeout) {
 $scope.thumbnail = [];
    $scope.showCanvasdiv = false;
    // Read the image using the filereader 
    $scope.fileReaderSupported = window.FileReader != null;
   $scope.ocular_file = function(files){
    if (files != null) {
        var file = files[0];
        if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
          $timeout(function() {
            var fileReader = new FileReader();
            fileReader.readAsDataURL(file); // convert the image to data url. 
            fileReader.onload = function(e) {
                $scope.showCanvasdiv = true;
              
              $timeout(function() {
               
                $scope.thumbnail.dataUrl = e.target.result; // Retrieve the image. 
                //console.log($scope.thumbnail.dataUrl);
              });
            }
          });
        }
      }
    };
    this.undo = function(){
       
          this.versionright--;
    };
});
</script>

我厌倦了使用auto,它使用指令工作正常。希望这会有所帮助。