将上传的图片旋转到90度

时间:2019-05-07 06:36:01

标签: javascript jquery canvas

我们为用户提供了一个上传图片的选项

我们还在顶部显示旋转按钮。...

要求

点击“旋转”按钮,图像应以Here的角度旋转90度。...

问题

图像随机旋转: Video link

下面是代码段:

$(document).ready(function() {

    //  base64string image format- to work in codepen, fiddle
	
    var maskedImageUrla = "https://i.imgur.com/TZwOgSa.png";
   
   // maskedImage 
    var mask1 = $(".container").mask({
        maskImageUrl: maskedImageUrla,
        onMaskImageCreate: function(img) {
            // add your style to the img example below
            img.css({
                "left": 105,
                "top": 5,
				"id": 'self'
            })
        }
    });

    fileupa1.onchange = function() {
        mask1.loadImage(URL.createObjectURL(fileupa1.files[0]));
    };
    
// Rotation code : 

let imageToSpin = document.getElementById('self');

var r = 0;
function spinImage() {
r+= 10;
	mask1.rotate(r) ;
}

btnTotate.onclick =spinImage;
    
}); // end of document ready

// jq code for mask

(function($) {
    var JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString() + JQmasks.length,
            x: 0, // image start position
            y: 0, // image start position
            onImageCreate: function(img) {},
            onMaskImageCreate: function(div) {},
            rotate: 0, // rotation
        }, options);

        var container = {};

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            div,
            rotate=settings.rotate,
            obj = $(this);
                              
        container.updateStyle = function() {

            context.clearRect(0, 0, canvas.width, canvas.height);
            context.globalCompositeOperation = "source-over";

            if (initImage || !image) {
                image = new Image();
                image.setAttribute('crossOrigin', 'anonymous');
                image.src = settings.maskImageUrl;
                image.onload = function() {
                    if (settings.onImageCreate)
                        settings.onImageCreate(image);

                    canvas.width = image.width * settings.scale;
                    canvas.height = image.height * settings.scale;
                    context.drawImage(image, 0, 0, image.width, image.height);
                    div.css({
                        "width": image.width,
                        "height": image.height
                    });
                };
            } else {
            // rotate the canvas to the specified degrees
             
                context.drawImage(image, 0, 0, image.width, image.height);
                
            }
             context.save();
             context.rotate(rotate);
            if (initImage || !img) {
                img = new Image();
                img.src = settings.imageUrl || "";
                img.setAttribute('crossOrigin', 'anonymous');
                img.onload = function() {
                    settings.x = settings.x === 0 && initImage === true ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
                    settings.y = settings.y === 0 && initImage === true ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
                    context.globalCompositeOperation = 'source-atop';
                    context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
                    initImage = false;
                };
            } else {
                context.globalCompositeOperation = 'source-atop';
                context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
            }
          
              context.restore();
        };

        // Rotation code : 

        container.rotate =function(r){
        rotate= r;
        container.updateStyle();
        }

        // change the draggable image
        container.loadImage = function(imageUrl) {
            if (img)
                img.remove();
            // reset the code.
            settings.y = startY;
            settings.x = startX;
            prevX = prevY = 0;
            settings.imageUrl = imageUrl;
            initImage = true;

            container.updateStyle();
        };

        container.createCanvas = function() {
            if (canvas)
                canvas.remove();
            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            div.append(canvas);
            div.find("canvas").hover(container.selected);
            div.find("canvas").on('touchstart mousedown', container.selected);
            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === true) return;
                event.handled = true;
                JQmasks.forEach(function(item) {
                    
                });
            });
            div.find("canvas").bind("dragover", container.onDragOver);
        };

        // change the masked Image
        container.loadMaskImage = function(imageUrl, from) {
            if (div)
                div.remove();

            settings.maskImageUrl = imageUrl;
            div = $("<div/>", {
                "class": "masked-img"
            });
            container.createCanvas();
            obj.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);
            container.loadImage(settings.imageUrl);
        };
        container.loadMaskImage(settings.maskImageUrl);
        JQmasks.push({
            item: container,
            id: settings.id
        });

        return container;
    };

}(jQuery));
.container {
    border: 1px solid #DDDDDD;
    display: flex;
    background: pink;
}

.container canvas {
    display: block;
}

.masked-img {
    overflow: hidden;
    margin-left: 10px;
    position: relative;
}

.rotated {
  transform: rotate(90deg)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

<input type="button" id="btnTotate" value="Rotate"/>

<br/><hr>

image 1 
<input id="fileupa1"  type="file" >

<div class="container">
</div>

这里是CodePen

如果您需要更多信息,请告诉我。...

2 个答案:

答案 0 :(得分:1)

画布上下文中的“旋转”功能接受的弧度角不是弧度。

如果必须将度数转换为弧度,请使用此radians = degree * Math.PI / 180

现在,即使这样做,您仍将从左上角旋转图像。如果必须防止这种情况并将其从中心旋转,则需要将画布平移到其中心。您可以通过

来实现
context.save()
context.translate(canvas.width / 2, canvas.height / 2)
context.rotate(rotate)
context.translate(-canvas.width / 2, -canvas.height / 2)
context.restore()

这将从画布中心旋转图像。如果要从图像中心旋转图像,请计算图像的中点并替换平移函数中的坐标。

$(document).ready(function() {

    //  base64string image format- to work in codepen, fiddle
	
    var maskedImageUrla = "https://i.imgur.com/TZwOgSa.png";
   
   // maskedImage 
    var mask1 = $(".container").mask({
        maskImageUrl: maskedImageUrla,
        onMaskImageCreate: function(img) {
            // add your style to the img example below
            img.css({
                "left": 105,
                "top": 5,
				"id": 'self'
            })
        }
    });

    fileupa1.onchange = function() {
        mask1.loadImage(URL.createObjectURL(fileupa1.files[0]));
    };
    
// Rotation code : 

let imageToSpin = document.getElementById('self');

var r = 0;
function spinImage() {
r+= 10;
	mask1.rotate(r) ;
}

btnTotate.onclick =spinImage;
    
}); // end of document ready

// jq code for mask

(function($) {
    var JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString() + JQmasks.length,
            x: 0, // image start position
            y: 0, // image start position
            onImageCreate: function(img) {},
            onMaskImageCreate: function(div) {},
            rotate: 0, // rotation
        }, options);

        var container = {};

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            div,
            rotate=settings.rotate,
            obj = $(this);
                              
        container.updateStyle = function() {

            context.clearRect(0, 0, canvas.width, canvas.height);
            context.globalCompositeOperation = "source-over";

            if (initImage || !image) {
                image = new Image();
                image.setAttribute('crossOrigin', 'anonymous');
                image.src = settings.maskImageUrl;
                image.onload = function() {
                    if (settings.onImageCreate)
                        settings.onImageCreate(image);

                    canvas.width = image.width * settings.scale;
                    canvas.height = image.height * settings.scale;
                    context.drawImage(image, 0, 0, image.width, image.height);
                    div.css({
                        "width": image.width,
                        "height": image.height
                    });
                };
            } else {
            // rotate the canvas to the specified degrees
             
                context.drawImage(image, 0, 0, image.width, image.height);
                
            }
             context.save();
             context.translate(canvas.width / 2, canvas.height / 2);
             context.rotate(rotate);
             context.translate(-canvas.width / 2, -canvas.height / 2);
            if (initImage || !img) {
                img = new Image();
                img.src = settings.imageUrl || "";
                img.setAttribute('crossOrigin', 'anonymous');
                img.onload = function() {
                    settings.x = settings.x === 0 && initImage === true ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
                    settings.y = settings.y === 0 && initImage === true ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
                    context.globalCompositeOperation = 'source-atop';
                    context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
                    initImage = false;
                };
            } else {
                context.globalCompositeOperation = 'source-atop';
                context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
            }
          
              context.restore();
        };

        // Rotation code : 

        container.rotate =function(r){
        rotate= r*Math.PI/180;
        container.updateStyle();
        }

        // change the draggable image
        container.loadImage = function(imageUrl) {
            if (img)
                img.remove();
            // reset the code.
            settings.y = startY;
            settings.x = startX;
            prevX = prevY = 0;
            settings.imageUrl = imageUrl;
            initImage = true;

            container.updateStyle();
        };

        container.createCanvas = function() {
            if (canvas)
                canvas.remove();
            canvas = document.createElement("canvas");
            context = canvas.getContext('2d');
            canvas.setAttribute("draggable", "true");
            canvas.setAttribute("id", settings.id);
            div.append(canvas);
            div.find("canvas").hover(container.selected);
            div.find("canvas").on('touchstart mousedown', container.selected);
            div.find("canvas").on('touchend mouseup', function(event) {
                if (event.handled === true) return;
                event.handled = true;
                JQmasks.forEach(function(item) {
                    
                });
            });
            div.find("canvas").bind("dragover", container.onDragOver);
        };

        // change the masked Image
        container.loadMaskImage = function(imageUrl, from) {
            if (div)
                div.remove();

            settings.maskImageUrl = imageUrl;
            div = $("<div/>", {
                "class": "masked-img"
            });
            container.createCanvas();
            obj.append(div);
            if (settings.onMaskImageCreate)
                settings.onMaskImageCreate(div);
            container.loadImage(settings.imageUrl);
        };
        container.loadMaskImage(settings.maskImageUrl);
        JQmasks.push({
            item: container,
            id: settings.id
        });

        return container;
    };

}(jQuery));
.container {
    border: 1px solid #DDDDDD;
    display: flex;
    background: pink;
}

.container canvas {
    display: block;
}

.masked-img {
    overflow: hidden;
    margin-left: 10px;
    position: relative;
}

.rotated {
  transform: rotate(90deg)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

<input type="button" id="btnTotate" value="Rotate"/>

<br/><hr>

image 1 
<input id="fileupa1"  type="file" >

<div class="container">
</div>

答案 1 :(得分:0)

我可以建议在服务器上安装imagemagick,然后将作为imagemagick一部分的mogrify命令作为shell命令运行。 Here是如何运行Shell命令的示例。

阅读mogrify手册页以获取旋转图像的语法。