IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Editeur d'image, fusionner deux images


Sujet :

JavaScript

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2015
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 28
    Localisation : France, Ardennes (Champagne Ardenne)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2015
    Messages : 49
    Points : 24
    Points
    24
    Par défaut Editeur d'image, fusionner deux images
    Bonjour.
    Je suis actuellement entrain de développer une application web qui permet d'éditer une photo :
    L'application sert a personnaliser des planches de skateboard.
    J'ai donc un canvas avec 2 images dedans : la planche de skateboard, et l'image que l'on veut imprimer dessus. L'image que l'on veut imprimer est mobile et redimensionnable.
    Mais maintenant nous n'avons aucune idée pour la suite. Comment faire pour créer une seule image ( le skateboard personnalisé ) à partir de ces 2 images ?

    Voici mon code :

    HTML
    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    <!DOCTYPE html>
    <html lang="en" class="no-js">
    	<head>
    		<meta charset="UTF-8" />
    		<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    		<meta name="viewport" content="width=device-width, initial-scale=1"> 
    		<title>Image Resizing with Canvas</title>
    		<link rel="stylesheet" type="text/css" href="css/normalize.css" />
    		<link rel="stylesheet" type="text/css" href="css/demo.css" />
    		<link rel="stylesheet" type="text/css" href="css/component.css" />
    		<!--[if IE]>
      		<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    		<![endif]-->
    	</head>
    	<body>
    		<div class="container">
    			<!-- Top Navigation -->
     
    			<div class="content">
    				<header class="codrops-header">
    					<h1>Image Resizing &amp; Cropping <br /><span>with Canvas</span></h1>
    				</header>
    				<div class="input">
     
    				<input type="file" id="file-input" name="imageLoader" onClick="test()"/>
     
     
     
    				</div>
     
    				<div class="component">
    					<div class="overlay">
    						<div class="overlay-inner">
    						</div>
    					</div>
     
    					<!-- This image must be on the same domain as the demo or it will not work on a local file system -->
    					<!-- http://en.wikipedia.org/wiki/Cross-origin_resource_sharing -->
    					<img  class="resize-image" src="img/" alt="image for resizing">
    					<img  class="board" src="img/boardnude.png" alt="image for resizing">
     
    				</div>
    				<div class="a-tip">
    					<p><strong>Hint:</strong> hold <span>SHIFT</span> while resizing to keep the original aspect ratio.</p>
    				</div>
     
    			</div><!-- /content -->
    			<!-- Related demos -->
     
    		</div> <!-- /container -->
    			<script src="js/jquery-2.1.1.min.js"></script>
    			<script src="js/component.js"></script>
    	</body>
    </html>

    Javascript
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    var resizeableImage = function(image_target) {
      // Some variable and settings
      var $container,
          orig_src = new Image(),
          image_target = $(image_target).get(0),
          event_state = {},
          constrain = false,
          min_width = 60, // Change as required
          min_height = 60,
          max_width = 800, // Change as required
          max_height = 900,
          resize_canvas = document.createElement('canvas');
     
      init = function(){
     
        // When resizing, we will always use this copy of the original as the base
        orig_src.src=image_target.src;
     
        // Wrap the image with the container and add resize handles
        $(image_target).wrap('<div class="resize-container"></div>')
        .before('<span class="resize-handle resize-handle-nw"></span>')
        .before('<span class="resize-handle resize-handle-ne"></span>')
        .after('<span class="resize-handle resize-handle-se"></span>')
        .after('<span class="resize-handle resize-handle-sw"></span>');
     
        // Assign the container to a variable
        $container =  $(image_target).parent('.resize-container');
     
        // Add events
        $container.on('mousedown touchstart', '.resize-handle', startResize);
        $container.on('mousedown touchstart', 'img', startMoving);
        $('.js-crop').on('click', crop);
      };
    /*-------------------------------------------------------------------------*/
     
    /*----------------------------------------------------------------------------------------------*/
      startResize = function(e){
        e.preventDefault();
        e.stopPropagation();
        saveEventState(e);
        $(document).on('mousemove touchmove', resizing);
        $(document).on('mouseup touchend', endResize);
      };
     
      endResize = function(e){
        e.preventDefault();
        $(document).off('mouseup touchend', endResize);
        $(document).off('mousemove touchmove', resizing);
      };
     
      saveEventState = function(e){
        // Save the initial event details and container state
        event_state.container_width = $container.width();
        event_state.container_height = $container.height();
        event_state.container_left = $container.offset().left; 
        event_state.container_top = $container.offset().top;
        event_state.mouse_x = (e.clientX || e.pageX || e.originalEvent.touches[0].clientX) + $(window).scrollLeft(); 
        event_state.mouse_y = (e.clientY || e.pageY || e.originalEvent.touches[0].clientY) + $(window).scrollTop();
     
    	// This is a fix for mobile safari
    	// For some reason it does not allow a direct copy of the touches property
    	if(typeof e.originalEvent.touches !== 'undefined'){
    		event_state.touches = [];
    		$.each(e.originalEvent.touches, function(i, ob){
    		  event_state.touches[i] = {};
    		  event_state.touches[i].clientX = 0+ob.clientX;
    		  event_state.touches[i].clientY = 0+ob.clientY;
    		});
    	}
        event_state.evnt = e;
      };
     
      resizing = function(e){
        var mouse={},width,height,left,top,offset=$container.offset();
        mouse.x = (e.clientX || e.pageX || e.originalEvent.touches[0].clientX) + $(window).scrollLeft(); 
        mouse.y = (e.clientY || e.pageY || e.originalEvent.touches[0].clientY) + $(window).scrollTop();
     
        // Position image differently depending on the corner dragged and constraints
        if( $(event_state.evnt.target).hasClass('resize-handle-se') ){
          width = mouse.x - event_state.container_left;
          height = mouse.y  - event_state.container_top;
          left = event_state.container_left;
          top = event_state.container_top;
        } else if($(event_state.evnt.target).hasClass('resize-handle-sw') ){
          width = event_state.container_width - (mouse.x - event_state.container_left);
          height = mouse.y  - event_state.container_top;
          left = mouse.x;
          top = event_state.container_top;
        } else if($(event_state.evnt.target).hasClass('resize-handle-nw') ){
          width = event_state.container_width - (mouse.x - event_state.container_left);
          height = event_state.container_height - (mouse.y - event_state.container_top);
          left = mouse.x;
          top = mouse.y;
          if(constrain || e.shiftKey){
            top = mouse.y - ((width / orig_src.width * orig_src.height) - height);
          }
        } else if($(event_state.evnt.target).hasClass('resize-handle-ne') ){
          width = mouse.x - event_state.container_left;
          height = event_state.container_height - (mouse.y - event_state.container_top);
          left = event_state.container_left;
          top = mouse.y;
          if(constrain || e.shiftKey){
            top = mouse.y - ((width / orig_src.width * orig_src.height) - height);
          }
        }
     
        // Optionally maintain aspect ratio
        if(constrain || e.shiftKey){
          height = width / orig_src.width * orig_src.height;
        }
     
        if(width > min_width && height > min_height && width < max_width && height < max_height){
          // To improve performance you might limit how often resizeImage() is called
          resizeImage(width, height);  
          // Without this Firefox will not re-calculate the the image dimensions until drag end
          $container.offset({'left': left, 'top': top});
        }
      }
     
      resizeImage = function(width, height){
        resize_canvas.width = width;
        resize_canvas.height = height;
        resize_canvas.getContext('2d').drawImage(orig_src, 0, 0, width, height);   
        $(image_target).attr('src', resize_canvas.toDataURL("image/png"));  
      };
     
      startMoving = function(e){
        e.preventDefault();
        e.stopPropagation();
        saveEventState(e);
        $(document).on('mousemove touchmove', moving);
        $(document).on('mouseup touchend', endMoving);
      };
     
      endMoving = function(e){
        e.preventDefault();
        $(document).off('mouseup touchend', endMoving);
        $(document).off('mousemove touchmove', moving);
      };
     
      moving = function(e){
        var  mouse={}, touches;
        e.preventDefault();
        e.stopPropagation();
     
        touches = e.originalEvent.touches;
     
        mouse.x = (e.clientX || e.pageX || touches[0].clientX) + $(window).scrollLeft(); 
        mouse.y = (e.clientY || e.pageY || touches[0].clientY) + $(window).scrollTop();
        $container.offset({
          'left': mouse.x - ( event_state.mouse_x - event_state.container_left ),
          'top': mouse.y - ( event_state.mouse_y - event_state.container_top ) 
        });
        // Watch for pinch zoom gesture while moving
        if(event_state.touches && event_state.touches.length > 1 && touches.length > 1){
          var width = event_state.container_width, height = event_state.container_height;
          var a = event_state.touches[0].clientX - event_state.touches[1].clientX;
          a = a * a; 
          var b = event_state.touches[0].clientY - event_state.touches[1].clientY;
          b = b * b; 
          var dist1 = Math.sqrt( a + b );
     
          a = e.originalEvent.touches[0].clientX - touches[1].clientX;
          a = a * a; 
          b = e.originalEvent.touches[0].clientY - touches[1].clientY;
          b = b * b; 
          var dist2 = Math.sqrt( a + b );
     
          var ratio = dist2 /dist1;
     
          width = width * ratio;
          height = height * ratio;
          // To improve performance you might limit how often resizeImage() is called
          resizeImage(width, height);
        }
      };
     
      crop = function(){
        //Find the part of the image that is inside the crop box
        var crop_canvas,
            left = $('.overlay').offset().left - $container.offset().left,
            top =  $('.overlay').offset().top - $container.offset().top,
            width = $('.overlay').width(),
            height = $('.overlay').height();
     
        crop_canvas = document.createElement('canvas');
        crop_canvas.id="mon_canvas";
        crop_canvas.width = width;
        crop_canvas.height = height;
     
        crop_canvas.getContext('2d').drawImage(image_target, left, top, width, height, 0, 0, width, height);
        window.open(crop_canvas.toDataURL("image/png"));
      }
     
      init();
     
     /*----------------------------------------------------------------------------------------------------------*/
     
     
     
    $(function() {
        $('#file-input').change(function(e) {
            var file = e.target.files[0];
     
            var reader = new FileReader();
            reader.onload = fileOnload;
            reader.readAsDataURL(file);        
        });
     
        function fileOnload(e) {
     
            var $img = $('<img>', { src: e.target.result });
            var canvas = document.getElementById("mon_canvas");
            var context = canvas.getContext('2d');
     
            $img.load(function() {
                context.drawImage(this, 10, 10, this.width, this.height);
            });
        }
    });  
    /*---------------------------------------------------------------------------------------------------------------*/
    };
    Je tiens à préciser que je ne connais pas parfaitement notre code car c'est un ami qui a suivi un tutoriel pour en arriver là.
    J'ai aussi un 2e soucis, nous avons créé un input de type "parcourir" afin d'ajouter au canvas l'image qui va personnaliser le skate. Mais nous n'avons jamais réussi à faire apparaitre cette image dans le canvas. Cela marche dans un 2e canvas, mais pas dans celui existant ..
    Cordialement,
    P4atch

  2. #2
    Membre émérite
    Inscrit en
    Septembre 2002
    Messages
    2 307
    Détails du profil
    Informations forums :
    Inscription : Septembre 2002
    Messages : 2 307
    Points : 2 814
    Points
    2 814
    Par défaut
    utilise des gif avec des fonds transparents! puis tape sur Impr écran....
    Sinon un javascript qui crée un fichier sur le pc client , ça ne se fait pas.

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2015
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 28
    Localisation : France, Ardennes (Champagne Ardenne)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2015
    Messages : 49
    Points : 24
    Points
    24
    Par défaut
    Ah mince ...
    Bon du coup j'abandonne l'idée d'enregistrer pour le moment.

    Mais pour ce qui est de mon bouton parcourir, je ne comprends pas pourquoi l'image ne s'ajoute pas a mon canvas.

    Le code correspondant au bouton parcourir :

    HTML :
    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    <input type="file" id="file-input" name="imageLoader" />

    JavaScript
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    var $container,
          orig_src = new Image(),
          image_target = $(image_target).get(0),
          event_state = {},
          constrain = false,
          min_width = 60, // Change as required
          min_height = 60,
          max_width = 800, // Change as required
          max_height = 900,
          resize_canvas = document.createElement('canvas');
     
    init = function(){
     
        // When resizing, we will always use this copy of the original as the base
        orig_src.src=image_target.src;
     
        // Wrap the image with the container and add resize handles
        $(image_target).wrap('<div class="resize-container"></div>')
        .before('<span class="resize-handle resize-handle-nw"></span>')
        .before('<span class="resize-handle resize-handle-ne"></span>')
        .after('<span class="resize-handle resize-handle-se"></span>')
        .after('<span class="resize-handle resize-handle-sw"></span>');
     
        // Assign the container to a variable
        $container =  $(image_target).parent('.resize-container');
     
        // Add events
        $container.on('mousedown touchstart', '.resize-handle', startResize);
        $container.on('mousedown touchstart', 'img', startMoving);
        $('.js-crop').on('click', crop);
      };
     
    $(function() {
        $('#file-input').change(function(e) {
            var file = e.target.files[0];
     
            var reader = new FileReader();
            reader.onload = fileOnload;
            reader.readAsDataURL(file);        
        });
     
        function fileOnload(e) {
     
            var $img = $('<img>', { src: e.target.result });
            var canvas = document.getElementById("mon_canvas");
            var context = canvas.getContext('2d');
     
            $img.load(function() {
                context.drawImage(this, 10, 10, this.width, this.height);
            });
        }
    });

  4. #4
    Membre expérimenté
    Homme Profil pro
    chomeur
    Inscrit en
    Avril 2015
    Messages
    709
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 79
    Localisation : France, Seine Maritime (Haute Normandie)

    Informations professionnelles :
    Activité : chomeur
    Secteur : Distribution

    Informations forums :
    Inscription : Avril 2015
    Messages : 709
    Points : 1 582
    Points
    1 582
    Par défaut
    l'enregistrement est tout a fait possible il suffit de convertir le contenu du canvas en base 64 avec toDataURL(); et on peut a ce moment soit cliquer sur l'image puis enregitrer sous pour l'enregistrer dans le pc soit utiliser ajax pour l'envoyer ver le serveur et la convertir en fichier image

    pour l'image dans le canvas sa ne sert a rien de creer une image et de refaire un onload il faut utiliser URL.createObjectURL de cette maniere on peut supprimer la fonction fileonload()

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    $(function() {
        $('#file-input').change(function(e) {
            var file = e.target.files[0];
     
            var mamage=window.URL.createObjectURL(file)
     
             var canvas = document.getElementById("mon_canvas");
             var context = canvas.getContext('2d');
     
             context.drawImage(mamage, 10, 10);
        });
    Plus vite encore plus vite toujours plus vite.

  5. #5
    Membre expérimenté
    Homme Profil pro
    chomeur
    Inscrit en
    Avril 2015
    Messages
    709
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 79
    Localisation : France, Seine Maritime (Haute Normandie)

    Informations professionnelles :
    Activité : chomeur
    Secteur : Distribution

    Informations forums :
    Inscription : Avril 2015
    Messages : 709
    Points : 1 582
    Points
    1 582
    Par défaut
    rectification de mon message precedent on ne peut pas directement mettre l'image dans le canvas avec createObjectURL il faut d’abord utiliser new Image ce qui donne

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
     
     $(function() {
     
        $('#file-input').change(function(e) {
     
            var file = e.target.files[0];
     
            var lien_file=window.URL.createObjectURL(file);
     
    	var ima=new Image();
    	ima.src=lien_file;
     
    	ima.onload=function () {
     
             var canvas = document.getElementById("cvs");
             var context = canvas.getContext('2d');
     
             context.drawImage(ima, 10, 10);
    	 }
     
        });
    certifié opérationnel
    Plus vite encore plus vite toujours plus vite.

Discussions similaires

  1. Fusionner deux images
    Par profx56 dans le forum WinDev
    Réponses: 1
    Dernier message: 11/09/2007, 11h36
  2. Fusionner deux images
    Par mimane_01 dans le forum Images
    Réponses: 21
    Dernier message: 17/05/2007, 16h59
  3. Fusionner deux images, en fonction d'une condition
    Par Him dans le forum Balisage (X)HTML et validation W3C
    Réponses: 2
    Dernier message: 27/01/2007, 14h07
  4. [GD] Fusionner deux images GD
    Par ~~PriVate JoKe~~ dans le forum Bibliothèques et frameworks
    Réponses: 9
    Dernier message: 11/12/2006, 18h04
  5. [ImageMagick] Fusionner deux images
    Par eagleleader dans le forum Bibliothèques et frameworks
    Réponses: 10
    Dernier message: 26/05/2006, 18h30

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo